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

4
我想在不使用命令提示符的情况下运行这个Node.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程序可以让我运行这个node js脚本并获取输出,而无需使用命令提示符。


2
“是的。”--由于您的问题非常模糊,这是唯一可能的答案。您需要提供更多关于您要做什么的信息,包括您想从哪个脚本或程序运行您的节点程序。 - Jeremy J Starcher
你可以使用supervisor。 - Subburaj
@JeremyJStarcher,我已经更新了我的问题。 - ameni
请点击此链接访问:http://supervisord.org/configuration.html - Subburaj
@CodePhobia 如果其他程序需要使用命令程序,则应该在后台运行,我不应该打开命令提示符。我正在使用Windows。 - ameni
显示剩余2条评论
1个回答

2

好的,根据提供的信息,这是我会做的事情。假设这是在你的开发环境中。

使用Mocha和Gulp来保持后台线程运行。

以下是需要执行的步骤:

  1. Include mocha dependency in your package.json

  2. Describe your activity to do be done in a test.js file. i.e. Run the other JS file in here. for e.g I used the following to test my db connection js file.

    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 }
    
  3. You need to use gulp to have a background process continually.

a. 在你的依赖项中包含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']);
});
b. npm install c. 在另一个命令窗口上运行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 script.js”。
我相信还有其他方法。如果你找到更简单的方法,请告诉我。

我所要做的是如何调用"node file.js",而不是何时调用它。我需要一种替代方法来从cmd运行nodejs命令。我想要从一个javascript程序中运行它。 - ameni
请检查编辑,我意识到我的建议很繁琐,但是如果您计划长期使用Node,学习Mocha/Gulp将是一件好事。 #仅供参考 - CodePhobia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接