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

后端 未结 5 994
感动是毒
感动是毒 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: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.

提交回复
热议问题