我想运行这个 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)运行这个脚本,任何其他允许我运行这个 Node js 脚本并在不使用命令提示符的情况下获取输出的程序 js。
最佳答案
好的,信息就这么给了你。这就是我会做的。假设这是在您的开发环境中。
将 Mocha 与 Gulp 结合使用以保持后台线程运行。
所以这就是你需要做的。
在您的
package.json
中包含 mocha 依赖项
在
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 }
您需要使用 gulp 来不断地进行后台处理。
一个。在你的依赖项中包含 gulp
和 gulp-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 安装
在单独的命令窗口中运行 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
。
我相信还有其他方法。如果您找到更简单的方法,请告诉我。
关于javascript - 自动启动和停止 node.js 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34262937/