自动启动和停止node.js脚本

时间:2015-12-14 08:58:31

标签: javascript node.js batch-file cmd

我想运行此节点。不使用命令提示符的js脚本:

    var spawn = require('child_process').spawn;
// Run node with the GenerateBlob.js file as an argument
var child = spawn('node', ['GenerateBlob.js']);
// Listen for any response from the child:
child.stdout.on('data', function (data) {
    var result = data.toString();
});
// Listen for any errors:
child.stderr.on('data', function (data) {
    console.log('There was an error: ' + data);
});

如何从其他javascript程序运行此脚本(我不是指child_process),任何其他程序js允许我运行此节点js脚本并在不使用命令提示符的情况下获取输出。

1 个答案:

答案 0 :(得分:2)

好的,所以给出了相关信息。这就是我要做的。假设这是你的开发环境。

使用Gocha与Gulp保持后台线程运行。

所以这就是你需要做的。

  1. package.json

  2. 中加入mocha依赖项
  3. 描述您要在test.js文件中完成的活动。 即在此处运行其他JS文件。 例如,我使用以下来测试我的数据库连接js文件。

    var assert = require('assert');
    var connect = require('./connect');
    var dbInterface = require('./interface');
    
    describe('dbInterface', function() {
    //Do Whatever you want to do with the interface.js File }
    
  4. 您需要使用gulp持续进行后台处理。

  5. 一个。在您的家属中加入gulpgulp-mocha

    在你的gulpfile.js让它连续运行你需要的东西,在这里我正在制作它,看看test.js和interface.js,即在它们的每次改变时重新运行测试。

    var gulp = require('gulp');
    var mocha = require('gulp-mocha');
    
    gulp.task('watch', function() {
      gulp.watch(['./test.js', './interface.js'], ['test']);
    });
    

    湾npm install

    ℃。在单独的命令窗口中运行npm run watch并继续您的日常工作。

    希望这会有所帮助。您可以在test.js文件中包含所需的任何逻辑。并调用你在其中引用的任何JS文件的任何必需函数。

    编辑:使用所需的代码。

    你可以这样制作当前的剧本,比如你的script.js

    exports.script = function(req,callback){
    //Your Script above.
        var spawn = require('child_process').spawn;
    // Run node with the GenerateBlob.js file as an argument
    var child = spawn('node', ['GenerateBlob.js']);
    // Listen for any response from the child:
    child.stdout.on('data', function (data) {
        var result = data.toString();
    });
    // Listen for any errors:
    child.stderr.on('data', function (data) {
        console.log('There was an error: ' + data);
    });
    });
    

    现在,在你的test.js

    里面
    var assert = require('assert');
    var childInterface= require('./script');
    
    describe('testingscript', function() {
    
      it('can run the script successfully', function(done) {
        childInterface.script(null, function(error) {
          assert.ifError(error);
          console.log('wahtever message');
        });
      });
    

    处理回调和参数。 如果你跑了,

    .\node_modules\.bin\mocha test.js
    

    您可以查看输出的结果,从技术上讲,您的文件上没有node srcipt.js

    我相信还有其他方法。如果你发现更容易的话,请告诉我。

相关问题