【问题标题】:node.js search by file namenode.js 按文件名搜索
【发布时间】:2018-09-02 22:35:58
【问题描述】:

我有这个程序打印给定目录中的文件列表,按文件扩展名过滤。我需要将其更改为一个程序,该程序在当前目录下搜索包含指定字符串(在文件名中)也由文件扩展名过滤的所有文件。基本上我需要第一个参数是文件名而不是目录路径,并且目录路径应该是当前目录而不是作为参数。

var fs = require('fs');
var path = require('path');
var dirPath = process.argv[2];  //directory path
var fileType = '.'+process.argv[3]; //file extension
var files = [];
fs.readdir(dirPath, function(err,list){
    if(err) throw err;
    for(var i=0; i<list.length; i++)
    {
        if(path.extname(list[i])===fileType)
        {
            console.log(list[i]); //print the file
            files.push(list[i]); //store the file name into the array files
        }
    }
});

【问题讨论】:

    标签: javascript node.js path


    【解决方案1】:
    try this code   
    var fs = require('fs');
        var path = require('path');
        var filename = '.'+process.argv[1]; //file extension
        var fileType = '.'+process.argv[2]; //file extension
        var files = [];
        fs.readdir(process.cwd(), function(err,list){
            if(err) throw err;
            for(var i=0; i<list.length; i++)
            {
                /*user your conditions AND/OR */
                if(path.extname(list[i])===fileType && list[i].indexOf(filename) != -1)
                {
                    console.log(list[i]); //print the file
                    files.push(list[i]); //store the file name into the array files
                }
            }
        });
    

    【讨论】:

      【解决方案2】:

      我建议为此使用 glob 包。请看:https://github.com/isaacs/node-glob

      例子:

      var glob = require("glob")
      
      // options is optional
      glob("**/*.js", options, function (er, files) {
        // files is an array of filenames.
        // If the `nonull` option is set, and nothing
        // was found, then files is ["**/*.js"]
        // er is an error object or null.
      })
      

      【讨论】:

        【解决方案3】:

        使用 __dirname 作为当前目录路径

        var fs = require('fs');
        var path = require('path');
        var dirPath = __dirname;//process.argv[2];  //directory path
        var fileType = '.'+process.argv[2]; //file extension
        var files = [];
        fs.readdir(dirPath, function(err,list){
            if(err) throw err;
            for(var i=0; i<list.length; i++)
            {
                if(path.extname(list[i])===fileType)
                {
                    console.log(list[i]); //print the file
                    files.push(list[i]); //store the file name into the array files
                }
            }
        });
        

        【讨论】:

          猜你喜欢
          • 2018-01-24
          • 1970-01-01
          • 2018-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-25
          • 1970-01-01
          相关资源
          最近更新 更多