用Node.js在dir中search文件
我目前正在尝试使用node
和grunt
在Windows上的特定文件夹中search几个文件。
我有一个grunt task
,它有一个读取带有JSON
文件的目录的函数,但问题是,当我运行任务时,读取文件的代码不会执行任何操作。那。 我不知道如果path的引用是正确的,但我也使用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 }
有没有人有一个想法,当我运行任务时为什么跳过这段代码? 我可能会错过一些基本的东西。 谢谢!
尝试readdirSync
并检查您的function是否仍然无法正常工作。 我想你的过程是在callback之前完成的。
您可以简单地使用__dirname
对象来获取当前脚本正在运行的path:
..// 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 }
你可以在这里find更多的信息。
你需要改变你的path
var filePath = path.normalize("C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports");
另外,要在任何操作系统上使用Windows文件path时获得一致的结果,请使用path.win32:
path.win32.basename('C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"');
你可以阅读有关https://nodejs.org/api/path.html#path_windows_vs_posix
路上的斜线正在逃脱。
"C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"
应该解决你的问题。