How do I get a list of files with specific file extension using node.js?

后端 未结 4 1381
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 00:37

The node fs package has the following methods to list a directory:

fs.readdir(path, [callback]) Asynchronous readdir(3). Reads the

4条回答
  •  猫巷女王i
    2020-12-31 01:16

    You could filter they array of files with an extension extractor function. The path module provides one such function, if you don't want to write your own string manipulation logic or regex.

    var path = require('path');
    
    var EXTENSION = '.txt';
    
    var targetFiles = files.filter(function(file) {
        return path.extname(file).toLowerCase() === EXTENSION;
    });
    

    EDIT As per @arboreal84's suggestion, you may want to consider cases such as myfile.TXT, not too uncommon. I just tested it myself and path.extname does not do lowercasing for you.

提交回复
热议问题