The directory all my files are in is: \'/usr/home/jordan\' and I have many files under there (in the directory itself, but one file that is named with a .txt extension.
var files = fs.readdirSync(homedir);
var path = require('path');
for(var i in files) {
if(path.extname(files[i]) === ".txt") {
//do something
}
}
You can use Glob Module as well. It works fine for me!
var glob = require( 'glob' );
var myPath= "/fileFolder/**/*.txt";
glob(myPath, function (er, files) {
// Files is an array of filenames.
// Do something with files.
})
The lazy solution:
npm install --save readdir
and then
const {read} = require('readdir');
read("/usr/home/jordan", "**/*.txt", (err, paths) =>
console.log(paths)
);
You can use fs.readdir and path.extname
var fs = require('fs')
, path = require('path');
function getFileWithExtensionName(dir, ext) {
fs.readdir(dir, function(files){
for (var i = 0; i < files.length; i++) {
if (path.extname(files[i]) === '.' + ext)
return files[i]
}
});
}
var homedir = "/usr/home/jordan";
var mytxtfilepath= getFileWithExtensionName(homedir, 'txt')
fs.readfile(mytxtfilepath, function(err,data) {
console.log(data);
});
You can use fs.readdir to list the files and find the one that ends with .txt
:
var myPath = "/usr/home/jordan";
fs.readdir(path, function(fileNames) {
for(var i = 0; i < fileNames.length; i++) {
var fileName = fileNames[i];
if(path.extname(fileName) === ".txt") {
fs.readfile(path.join(myPath,fileName), function(err,data) {
console.log(data);
});
break;
}
}
}
);
Note this requires path so add var path = require("path")
at the top.