2016-09-20 79 views
1

我正在尝试使用nodegrunt搜索Windows上特定文件夹中的几个文件。使用Node.js在dir中搜索文件

我有一个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

您的正斜杠正在转义您的路径名称 –

+0

使用“C:\\ Users \\ ...”或“C:/ Users /” – Draykos

回答

2

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

+0

似乎您是正确的,我尝试了它并正在工作!我们会看到另一种方式来阅读Async以获得最佳实践。 –

0

你需要改变你的路径

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

0

路径中的斜线正在逃脱。

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

应该解决您的问题。

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