自动启动和停止node.js脚本
我想运行这个节点。 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脚本,并获得输出,而不使用命令提示符。
好的,给出的信息。 这是我会做的。 假设这是你的开发环境。
使用Mocha与Gulp保持后台线程运行。
所以这是你需要做的。
-
在你的
package.json
包含摩卡依赖 -
描述你的活动在
test.js
文件中完成。 即在这里运行其他JS文件。 例如我使用以下来testing我的db连接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 }
-
您需要使用gulp来持续进行后台进程。
一个。 在您的依赖中包含一些gulp
和gulp-mocha
。
在你的gulpfile.js
有它运行的任何你需要的不断,在这里我正在看它的test.js和interface.js,即在他们的每一个变化重新运行testing。
var gulp = require('gulp'); var mocha = require('gulp-mocha'); gulp.task('watch', function() { gulp.watch(['./test.js', './interface.js'], ['test']); });
湾 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'); }); });
照顾callback和params。 之后如果你跑步,
.\node_modules\.bin\mocha test.js
你可以看到输出的结果是什么,技术上你没有在你的文件上运行node srcipt.js
。
我相信还有其他的方法。 请让我知道,如果你find更容易的一个。