2016-04-18 67 views
0

我正在使用node.js.我想遍歷所有帶有擴展名爲.coffee, 的文件,但我沒有找到任何實例。有人能幫助我嗎?獲取具有指定擴展名的所有文件node.js

在此先感謝!

+0

您正在使用什麼操作系統? * nix味道,Mac或Windows? – NZD

+0

@NZD我正在使用Arch Linux,但如果它在Windows和Mac上也可以使用,我會很高興。 –

+0

您可能正在尋找['fs.readdir()'](https://nodejs.org/api/fs.html#fs_fs_readdir_path_callback),也許正在尋找[''path.extname()'](https:// nodejs。組織/ API/path.html#path_path_extname_p)。 – jfriend00

回答

1

以下函數將使用提供的正則表達式返回指定目錄中的所有文件。

功能

var path = require('path'), fs=require('fs'); 

function fromDir(startPath,filter,callback){ 

    //console.log('Starting from dir '+startPath+'/'); 

    if (!fs.existsSync(startPath)){ 
     console.log("no dir ",startPath); 
     return; 
    } 

    var files=fs.readdirSync(startPath); 
    for(var i=0;i<files.length;i++){ 
     var filename=path.join(startPath,files[i]); 
     var stat = fs.lstatSync(filename); 
     if (stat.isDirectory()){ 
      fromDir(filename,filter,callback); //recurse 
     } 
     else if (filter.test(filename)) callback(filename); 
    }; 
}; 

使用

fromDir('../LiteScript',/\.coffee$/,function(filename){ 
    console.log('-- found: ',filename); 
}); 
+0

看到jffriend00對easyer這樣做的評論,但是也很好,:) –

相關問題