How to use child_process - 10 common examples

To help you get started, we’ve selected a few child_process examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ioBroker / ioBroker.simple-api / test / lib / setup.js View on Github external
setTimeout(function () {
                client.destroy();
                if (!fs.existsSync(rootDir + 'tmp/node_modules/' + appName + '.js-controller')) {
                    console.log('installJsController: no js-controller => install from git');

                    child_process.execSync('npm install https://github.com/' + appName + '/' + appName + '.js-controller/tarball/master --prefix ./  --production', {
                        cwd:   rootDir + 'tmp/',
                        stdio: [0, 1, 2]
                    });
                } else {
                    console.log('Setup js-controller...');
                    let __pid;
                    if (debug) {
                        // start controller
                        child_process.exec('node ' + appName + '.js setup first', {
                            cwd: rootDir + 'tmp/node_modules/' + appName + '.js-controller',
                            stdio: [0, 1, 2]
                        });
                    } else {
                        child_process.fork(appName + '.js', ['setup', 'first'], {
                            cwd:   rootDir + 'tmp/node_modules/' + appName + '.js-controller',
                            stdio: [0, 1, 2, 'ipc']
                        });
                    }
                }

                // let npm install admin and run setup
                checkIsControllerInstalled(function () {
                    let _pid;

                    if (fs.existsSync(rootDir + 'node_modules/' + appName + '.js-controller/' + appName + '.js')) {
github ioBroker / ioBroker.iot / test / lib / setup.js View on Github external
console.log('Install adapter...');
    var startFile = 'node_modules/' + appName + '.js-controller/' + appName + '.js';
    // make first install
    if (debug) {
        child_process.execSync('node ' + startFile + ' add ' + customName + ' --enabled false', {
            cwd:   rootDir + 'tmp',
            stdio: [0, 1, 2]
        });
        checkIsAdapterInstalled(function (error) {
            if (error) console.error(error);
            console.log('Adapter installed.');
            if (cb) cb();
        });
    } else {
        // add controller
        var _pid = child_process.fork(startFile, ['add', customName, '--enabled', 'false'], {
            cwd:   rootDir + 'tmp',
            stdio: [0, 1, 2, 'ipc']
        });

        waitForEnd(_pid, function () {
            checkIsAdapterInstalled(function (error) {
                if (error) console.error(error);
                console.log('Adapter installed.');
                if (cb) cb();
            });
        });
    }
}
github googleapis / cloud-trace-nodejs / test / non-interference / express-e2e.js View on Github external
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

var assert = require('assert');
var cp = require('child_process');
var glob = require('glob');
var path = require('path');
var tmp = require('tmp');

var expressVersion = '4.15.3';

// Setup
var express_dir = tmp.dirSync().name;
cp.execFileSync('git', ['clone', '--branch', expressVersion,
    'https://github.com/strongloop/express.git', '--depth', '1', express_dir]);
var test_glob = path.join(express_dir, 'test', '*.js');
var error;
process.chdir(express_dir);

// Remove name to allow for cyclic dependency
console.log('Updating express metadata');
cp.execFileSync('sed', ['-i.bak', 's/"express"/"e"/', 'package.json']);

// Install express as its own dependency
console.log('Installing express dependencies');
cp.execFileSync('npm', ['--version'], { stdio: 'inherit' });
cp.execFileSync('npm', ['install']);
cp.execFileSync('npm', ['install', 'express@' + expressVersion]);

// Reformat tests to use newly installed express
github graalvm / graaljs / test / parallel / test-child-process-constructor.js View on Github external
const child = new ChildProcess();

  [null, 0, 1, NaN, true, false, {}, 'foo'].forEach((args) => {
    common.expectsError(() => {
      child.spawn({ file: 'foo', args });
    }, {
      code: 'ERR_INVALID_ARG_TYPE',
      type: TypeError,
      message: 'The "options.args" property must be of type Array. ' +
               `Received type ${typeName(args)}`
    });
  });
}

// Test that we can call spawn
const child = new ChildProcess();
child.spawn({
  file: process.execPath,
  args: ['--interactive'],
  cwd: process.cwd(),
  stdio: 'pipe'
});

assert.strictEqual(child.hasOwnProperty('pid'), true);
assert(Number.isInteger(child.pid));

// Try killing with invalid signal
common.expectsError(
  () => { child.kill('foo'); },
  { code: 'ERR_UNKNOWN_SIGNAL', type: TypeError }
);
github graalvm / graaljs / test / parallel / test-child-process-constructor.js View on Github external
'use strict';

const common = require('../common');
const assert = require('assert');
const { ChildProcess } = require('child_process');
assert.strictEqual(typeof ChildProcess, 'function');

function typeName(value) {
  return typeof value;
}

{
  // Verify that invalid options to spawn() throw.
  const child = new ChildProcess();

  [undefined, null, 'foo', 0, 1, NaN, true, false].forEach((options) => {
    common.expectsError(() => {
      child.spawn(options);
    }, {
      code: 'ERR_INVALID_ARG_TYPE',
      type: TypeError,
      message: 'The "options" argument must be of type Object. ' +
               `Received type ${typeName(options)}`
    });
  });
}

{
  // Verify that spawn throws if file is not a string.
  const child = new ChildProcess();
github dudewheresmycode / GifTuna / app / main.js View on Github external
// var input = prefs.file.input;
  var w = prefs.dimensions.width || 320;
  var h = prefs.dimensions.height || 240;
  var fps = prefs.fps || 24;
  var stats = prefs.color.stats_mode || 'full';
  // var colors = prefs.color.colors || 256;
  var transparency = (prefs.color.alpha?1:0) || 0;
  var colors = prefs.color.count || 256;

  var scaleCmd = "scale="+w+":"+h;

  var vf = util.format("fps=%s,%s:flags=lanczos,palettegen=stats_mode=%s:max_colors=%s:reserve_transparent=%s", fps, scaleCmd, stats, colors, transparency);

  if(ffmpeg_ps) ffmpeg_ps.kill();

  ffmpeg_ps = spawn(ffmpeg_path, ["-i", input, "-vf", vf, "-f", "image2", "-vcodec", "png", "pipe:1"])
  var data = [];
  ffmpeg_ps.stdout.on('data',function(d){
    data.push(d);
  });
  ffmpeg_ps.stderr.on('data',function(d){
    // console.log("stderr",d.toString());
  });
  ffmpeg_ps.on('close',function(){
    event.sender.send('paletteResult', Buffer.concat(data).toString('base64'));
  });
})
ipcMain.on('cancelProcess', (event,opts) => {
github hypery2k / nativescript-fabric / src / scripts / build-native.js View on Github external
const { exec } = require('child_process');
const semver = require('semver');

const currentDir = process.cwd();

exec('tns --version', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    console.log(`tns --version err: ${err}`);
    return;
  }

  const tnsVersion = semver.major(stdout);

  // execute 'tns plugin build' for {N} version > 4. This command builds .aar in platforms/android folder.
  if (tnsVersion >= 4) {
    console.log(`executing 'tns plugin build' in ${currentDir}`);
    exec(`cd ${currentDir} && tns plugin build`);
  }
});
github react-static / react-static / packages / react-static / src / commands / create.js View on Github external
await fs.move(path.join(dest, 'gitignore'), path.join(dest, '.gitignore'))
  }
  if (fs.pathExistsSync(path.join(dest, 'gitignore'))) {
    fs.removeSync(path.join(dest, 'gitignore'))
  }

  if (isCLI) {
    console.log(
      `Installing dependencies with: ${
        isYarn
          ? chalk.hex(ChalkColor.yarn)('Yarn')
          : chalk.hex(ChalkColor.npm)('NPM')
      }...`
    )
    // We install react-static separately to ensure we always have the latest stable release
    execSync(`cd "${name}" && ${isYarn ? 'yarn' : 'npm install'}`)
    console.log('')
  }

  timeEnd(chalk.green(`[\u2713] Project "${name}" created`))

  console.log(`
  ${chalk.green('To get started:')}

    cd "${name}" ${
    !isCLI
      ? `&& ${
          isYarn
            ? chalk.hex(ChalkColor.yarn)('yarn')
            : chalk.hex(ChalkColor.npm)('npm install')
        }`
      : ''
github konstellation-io / science-toolkit / vscode / extensions / ms-vscode.go-0.13.0 / out / src / util.js View on Github external
if (process.platform === 'win32') {
        const TASK_KILL = 'C:\\Windows\\System32\\taskkill.exe';
        // when killing a process in Windows its child processes are *not* killed but become root processes.
        // Therefore we use TASKKILL.EXE
        try {
            cp.execSync(`${TASK_KILL} /F /T /PID ${processId}`);
        }
        catch (err) {
            console.log('Error killing process tree: ' + err);
        }
    }
    else {
        // on linux and OS X we kill all direct and indirect child processes as well
        try {
            const cmd = path.join(__dirname, '../../../scripts/terminateProcess.sh');
            cp.spawnSync(cmd, [processId.toString()]);
        }
        catch (err) {
            console.log('Error killing process tree: ' + err);
        }
    }
}
exports.killTree = killTree;
github expo / xde / src / application / PackagerController.js View on Github external
let cliOpts = ['start',
      '--port', this.opts.packagerPort,
      '--projectRoots', root,
      '--assetRoots', root,
    ];

    if (options.reset) {
      cliOpts.push('--reset-cache');
    }
    
    // Run the copy of Node that's embedded in Electron by setting the
    // ELECTRON_RUN_AS_NODE environment variable
    // Note: the CLI script sets up graceful-fs and sets ulimit to 4096 in the
    // child process
    let packagerProcess = child_process.fork(this.opts.cliPath, cliOpts, {
      cwd: path.dirname(path.dirname(this.opts.cliPath)),
      env: {
        ...process.env,
        NODE_PATH: null,
        ELECTRON_RUN_AS_NODE: 1,
      },
      silent: true,
    });
    process.on('exit', () => {
      packagerProcess.kill();
    });
    this._packager = packagerProcess;
    this._packager.stdout.setEncoding('utf8');
    this._packager.stderr.setEncoding('utf8');
    this._packager.stdout.on('data', (data) => {
      this.emit('stdout', data);

child_process

This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it.

ISC
Latest version published 8 years ago

Package Health Score

68 / 100
Full package analysis