我试图在一个 grunt 插件中创建一个流,但失败得很惨......
此代码用作独立 Node 脚本:
var fs = require('fs');
var sourceFile = 'testfile.log';
fs
.createReadStream( sourceFile )
.on('data', function() {
console.log('getting data');
})
.on('end', function() {
console.log('end!');
});
输出
$ node test.js
getting data
end!
现在将其放入 grunt 插件时:
'use strict';
var fs = require('fs');
module.exports = function(grunt) {
grunt.registerMultiTask('test', 'Testing streams', function() {
var sourceFile = 'testfile.log';
fs
.createReadStream( sourceFile )
.on('data', function() {
console.log('getting data');
grunt.log.oklns('anything?');
})
.on('end', function() {
console.log('end!');
grunt.log.oklns('nothing?');
});
});
};
输出
$ grunt test
Running "test" (test) task
Done, without errors.
我正在测试:
var stats = fs.lstatSync( sourceFile );
if( !stats.isFile() ) { /*etc*/ }
如果文件存在但我的 Node 测试应用程序在同一个文件夹中并且可以访问...任何帮助表示赞赏。我知道这一定不是很难做 ;)
最佳答案
您正在 Grunt 任务中使用异步代码。这样做时,您必须告诉 grunt 等待它完成。这是通过以下方式完成的:
// Within the task
var done = this.async();
// inside a callback of an async function,
// i.e. when the read stream is closed */
function(){
done(true);
}
以 true 条件调用 done 告诉 Grunt 任务已完成。如果未调用 this.async()
,任务将同步执行。在您的情况下,grunt 任务在读取流接收到任何数据之前完成。
您可以阅读有关此特定功能的更多信息 here (inside-tasks#this.async) .
附带说明一下,您提供的代码将任务注册为多任务,但代码(至少在其当前状态下)是基本任务而不是多任务。您可以在官方文档中了解差异 here (basic tasks)和 here (multi tasks) .
关于javascript - 如何在 grunt 插件中运行 createReadStream(a stream)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30064513/