如何在grunt插件中运行createReadStream(流)?

时间:2015-05-05 22:46:40

标签: javascript node.js gruntjs grunt-plugins

我正在尝试在grunt插件中创建一个流并且悲惨地失败......

此代码用作独立的节点脚本:

btnSend.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent arg0) {
        String fileContents;
        a = System.currentTimeMillis();
        try {
            fileContents = control.getFileContents(txtSearch.getText());
            b = System.currentTimeMillis();
            txtView.setText(fileContents + "\n" + "\n" + "The process took "+(b-a)+"milliseconds to execute." + "\n" + "("+((b-a)/1000)+" seconds)");

        } catch (RemoteException e) {
            txtView.setText("File not found");
        }

    }

输出

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!

输出

'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.

如果该文件存在,但我的节点测试应用程序位于同一文件夹中并且具有访问权限...感谢任何帮助。我知道它不是很难做到;)

1 个答案:

答案 0 :(得分:3)

您在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条件调用告诉Grunt任务已完成。如果未调用this.async(),则任务将同步执行。在您的情况下,grunt任务在读取流接收任何数据之前完成。

您可以阅读有关此特定功能的更多信息here (inside-tasks#this.async)

作为旁注,您提供的代码将任务注册为多任务,但代码(至少在其当前状态下)是基本任务而不是多任务。您可以在官方文档here (basic tasks)here (multi tasks)中了解差异。