Starting and stopping the node.js script automatically

I want to run this node. js script without using command line:

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

How can I run this script from another javascript program (I don't mean child_process), any other js program that allows me to run this node js script and get output without using the command line.

+4
source share
1 answer

Good, so give information. This is what I would do. Suppose this is in your dev environment.

Using Mocha with Gulp to save a background thread.

So this is what you need to do.

  • Turn the mocha dependency into package.json

  • , test.js. 1. JS . , , js db.

    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 i.e .

var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('watch', function() {
  gulp.watch(['./test.js', './interface.js'], ['test']);
});

. npm install

. npm run watch .

, . test.js. JS , .

: .

script , , 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 .

, . , .

+2

Source: https://habr.com/ru/post/1619824/


All Articles