Last active
December 23, 2020 20:57
-
-
Save wheresjames/fb31293c623c9ef2a33df0142453a85e to your computer and use it in GitHub Desktop.
Install global npm dependencies from package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/node | |
const fs = require('fs'); | |
const path = require('path'); | |
const shell = require('shelljs'); | |
const cp = require('child_process'); | |
const c_Usage = "USAGE: ./npm-global-install.js <path-to-package.json>"; | |
const c_start_time = new Date().getTime() / 1000; | |
function Log() | |
{ | |
let t = new Date().getTime() / 1000; | |
console.log(`[${(t-c_start_time).toFixed(3)}]`, ...arguments); | |
} | |
function npmInstall(deps) | |
{ | |
if (!deps) | |
{ | |
Log("No dependencies"); | |
return false; | |
} | |
Log('Installing : ', deps.join(', ')); | |
// Install dependencies | |
let sub = cp.spawn('npm', ['install', '--global'].concat(deps), | |
{ | |
stdio: ['ignore', process.stdio, process.stderr] | |
}); | |
sub.on('exit', (code) => | |
{ Log(`npm exited with code: ${code}`); | |
if (code) | |
process.exit(code); | |
}); | |
return true; | |
} | |
function getDeps(pf) | |
{ | |
let data = JSON.parse(fs.readFileSync(pf, 'utf8')); | |
let deps = []; | |
for (let k in data['dependencies']) | |
deps.push(`${k}@${data['dependencies'][k]}`); | |
for (let k in data['devDependencies']) | |
deps.push(`${k}@${data['devDependencies'][k]}`); | |
return deps; | |
} | |
function main() | |
{ | |
// Ensure parameters | |
if (process.argv.length <= 2) | |
{ | |
Log(c_Usage); | |
process.exit(-1); | |
} | |
let pf = process.argv[2]; | |
if (!fs.existsSync(pf)) | |
{ | |
Log(`File not found : ${pf}`); | |
process.exit(-1); | |
} | |
Log(`Installing dependencies from ${pf}`); | |
let deps = getDeps(pf); | |
npmInstall(deps); | |
return 0; | |
} | |
// Exit handling | |
process.on('cleanup',function() { Log('~ cleanup ~');}); | |
process.on('exit',function() { Log('~ exit ~');}); | |
process.on('SIGINT',function() { Log('~ ctrl+c ~'); process.exit(-1); }); | |
process.on('uncaughtException',function(e) { Log('~ uncaught ~', e); process.exit(-1); }); | |
return main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment