среда, 6 сентября 2017 г.

Node.js Spawn NPM install dependecies

Файл install.js

var child_process = require('child_process')
    , package = require('./package');

var dependencies = []
    , preinstall;

if (package.hasOwnProperty('dependencies')) {
    for (var key in package.dependencies) {
        if (package.dependencies.hasOwnProperty(key)) {
            dependencies.push(key + '@' + package.dependencies[key]);
        }
    }
}

if (package.hasOwnProperty('devDependencies')) {
    for (var key in package.devDependencies) {
        if (package.devDependencies.hasOwnProperty(key)) {
            dependencies.push(key + '@' + package.devDependencies[key]);
        }
    }
}

if (package.hasOwnProperty('scripts') && package.scripts.hasOwnProperty('preinstall')) {
    preinstall = package.scripts.preinstall;
    if (preinstall.indexOf('npm i ') === 0) {
        preinstall = preinstall.slice(6);
    }
}

dependencies.sort();

installNextDependency(dependencies);

function installNextDependency (dependencies) {
    var dependency = dependencies.pop()
        , parameters;
    if (typeof dependency === 'string') {
        parameters = ['install', dependency];
    } else if (typeof dependency === 'undefined' && typeof preinstall === 'string') {
        parameters = ['install', preinstall];
        preinstall = undefined;
    } else {
        console.log('The end. Dependencies array and scripts preinstall are empty.');
        return;
    }
    var spawnProcess = child_process.spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', parameters, {stdio: 'inherit', shell: true});
    spawnProcess.on('exit', function (code) {
        if (code === 0) {
            console.log('Dependency ' + parameters[1] + ' installed.');
            installNextDependency(dependencies);
        } else {
            console.log('Error in dependency: ' + parameters[1] + '.');
            console.log('Error. Exited with code: ' + code + '.');
        }
    });
    spawnProcess.on('error', function (error) {
        console.log('Error in dependency: ' + parameters[1] + '.');
        throw error;
    });
}

/*
// Test NPM
var child_process = require('child_process');
var spawnProcess = child_process.spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['--version'], {stdio: 'inherit', shell: true});
spawnProcess.on('exit', function (code) {
    if (code === 0) {
        console.log('Done');
    } else {
        console.log('Error. Exited with code: ' + code);
    }
});
spawnProcess.on('error', function (error) {
    throw error;
});
*/

Комментариев нет:

Отправить комментарий