2015-12-14 183 views
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,讓我跑這個節點js腳本,並得到輸出:不使用命令提示符js腳本而不使用命令提示符。

+2

「是的。「 - 你的問題含糊不清,這是唯一可能的答案,你需要提供更多關於你想要做什麼的信息,包括你想要運行節點程序的腳本或程序。 –

+0

你可以使用主管.. – Subburaj

+0

@JeremyJStarcher我已經更新了我的問題 – ameni

回答

2

好的,所以給出的信息。這是我會做的。假設這是你的開發環境。

使用Mocha和Gulp保持後臺線程運行。

所以這就是你需要做的。

  1. 包括在你的package.json

  2. 摩卡依賴描述您的活動做一個test.js文件來完成。 即在這裏運行其他JS文件。 例如我使用以下來測試我的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 } 
    
  3. 您需要使用一口有一個後臺進程不斷。

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'); 
    }); 
    }); 

採取回調,而params的照顧。 這個,如果你運行後,

.\node_modules\.bin\mocha test.js 

你可以看到的結果是什麼輸出和技術上你是不是在你的文件上運行node srcipt.js

我相信還有其他的方法。如果您發現更容易的一個,請告訴我。

+0

我想完成的是如何調用「node file.js」而不是何時調用它。我需要一個替代方法來運行nodejs命令從cmd。我想從一個javascript程序運行它。 – ameni

+0

請檢查編輯,我意識到我所建議的是繁瑣的,但如果您計劃長期堅持節點,學習摩卡/吞嚥將是一件長期的好事。 #JustMy2Cents – CodePhobia