How to get the first file with a .txt extension in a directory with nodejs?

后端 未结 5 990
感动是毒
感动是毒 2021-02-20 14:06

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.

相关标签:
5条回答
  • 2021-02-20 14:15
    var files = fs.readdirSync(homedir);
    var path = require('path');
    
    for(var i in files) {
       if(path.extname(files[i]) === ".txt") {
           //do something
       }
    }
    
    0 讨论(0)
  • 2021-02-20 14:36

    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.
    })
    
    0 讨论(0)
  • 2021-02-20 14:38

    The lazy solution:

    npm install --save readdir
    

    and then

    const {read} = require('readdir');
    read("/usr/home/jordan", "**/*.txt", (err, paths) =>
        console.log(paths)
    );
    
    0 讨论(0)
  • 2021-02-20 14:40

    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);
    });
    
    0 讨论(0)
  • 2021-02-20 14:42

    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.

    0 讨论(0)
提交回复
热议问题