我目前正在尝试使用node
和grunt
在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
}
有没有人知道为什么在运行任务时会跳过这段代码?我可能会遗漏一些基本的东西。谢谢!
答案 0 :(得分:2)
尝试readdirSync
并检查您的功能是否仍然有效。我想你的过程在回调之前完成了。
答案 1 :(得分:1)
您只需使用__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。
答案 2 :(得分:0)
你需要改变你的路径
var filePath = path.normalize("C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports");
另外,要在任何操作系统上使用Windows文件路径时获得一致的结果,请使用path.win32:
path.win32.basename('C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"');
答案 3 :(得分:0)
路径中的斜线正在转义。
"C:\\Users\\jbernhardt\\Desktop\\testkeeper\\jenkinsReports"
应解决您的问题。