【问题标题】:Starting and Stopping node.js script automatically自动启动和停止 node.js 脚本
【发布时间】:2016-03-19 16:36:27
【问题描述】:

我想运行这个节点。 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 运行此脚本。

【问题讨论】:

  • “是的。” - 与您的问题一样模糊,这是唯一可能的答案。您需要提供更多有关您尝试执行的操作的信息,包括您想从哪个脚本或程序运行节点程序。
  • 你可以使用supervisor..
  • @JeremyJStarcher 我更新了我的问题
  • @Subburaj 你有例子吗?
  • 其他程序可以使用命令提示符吗?或者你想要点击类型?您使用的是哪种操作系统/环境?

标签: javascript node.js batch-file cmd


【解决方案1】:

好的,所以给出了信息。这就是我会做的。假设这是在您的开发环境中。

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

所以这就是你需要做的。

  1. package.json 中包含 mocha 依赖项

  2. 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 }
    
  3. 您需要使用 gulp 来持续拥有后台进程。

一个。在您的依赖项中包含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 安装

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 srcipt.js

我相信还有其他方法。如果您找到更简单的方法,请告诉我。

【讨论】:

  • 我想要完成的是如何调用“node file.js”而不是何时调用它。我需要从 cmd 运行 nodejs 命令的替代方法。我想从 javascript 程序中运行它。
  • 请检查编辑,我知道我的建议很麻烦,但是如果您打算长期坚持使用节点,那么长期学习 mocha/gulp 将是一件好事。 #JustMy2Cents
猜你喜欢
  • 2012-09-05
  • 1970-01-01
  • 2014-07-07
  • 2020-06-22
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
相关资源
最近更新 更多