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

后端 未结 5 988
感动是毒
感动是毒 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: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);
    });
    

提交回复
热议问题