使用 Node.js 在目录中搜索文件

Searching files in dir with Node.js

我目前正在尝试使用 nodegrunt 在 Windows 上的特定文件夹中搜索一些文件。

我有一个 grunt task 具有读取目录 JSON 文件的功能,但问题是当我 运行 任务时,读取文件的代码什么都不做,grunt task 运行 上的其他一切都很完美,但是。我不确定路径的引用是否正确,但我也使用 path.normalize() 并且它不会引发任何错误。

这是代码片段:

..// Some other code
var fs = require('fs'),
path = require("path");

grunt.registerTask('separate', function() {
var filePath = path.normalize("C:\Users\jbernhardt\Desktop\testkeeper\jenkinsReports");

fs.readdir(filePath, function(err, filenames) {

  //This log doesn't show as it the function is not running
  grunt.log.writeln("Testing");

    if (err) {
        grunt.log.writeln("Error");
        return;
    }
    filenames.forEach(function(filename){
        grunt.log.writeln("Testing");

    });

  });
...//Some more code below for the same task
}

有谁知道为什么我 运行 任务时会跳过这段代码?我可能会遗漏一些基本的东西。谢谢!

您需要更改路径

var filePath = path.normalize("C:\Users\jbernhardt\Desktop\testkeeper\jenkinsReports");

此外,要在任何操作系统上使用 Windows 文件路径时获得一致的结果,请使用 path.win32:

path.win32.basename('C:\Users\jbernhardt\Desktop\testkeeper\jenkinsReports"');

您可以阅读有关 https://nodejs.org/api/path.html#path_windows_vs_posix

尝试 readdirSync 并检查您的功能是否仍然无法正常工作。我猜你的进程在回调之前就完成了。

正在转义路径中的斜杠。

"C:\Users\jbernhardt\Desktop\testkeeper\jenkinsReports" 

应该可以解决您的问题。

你可以简单地使用__dirname对象来获取当前脚本所在的路径运行:

..// Some other code
var fs = require('fs'),
path = require("path");

grunt.registerTask('separate', function() {

fs.readdir(__dirname, function(err, filenames) {

  //This log doesn't show as it the function is not running
  grunt.log.writeln("Testing");

    if (err) {
        grunt.log.writeln("Error");
        return;
    }
    filenames.forEach(function(filename){
        grunt.log.writeln("Testing");

    });

  });
...//Some more code below for the same task
}

您可以找到更多信息 here