Skip to content

Instantly share code, notes, and snippets.

@ryancat
Last active April 4, 2019 00:40
Show Gist options
  • Save ryancat/3e0e134833662b8441b055fac6f9f8f8 to your computer and use it in GitHub Desktop.
Save ryancat/3e0e134833662b8441b055fac6f9f8f8 to your computer and use it in GitHub Desktop.
Run npm install in all packages defined by lerna.json
// Assume this file is next to lerna.json
// Otherwise the path to lerna.json needs to be updated (line 9)
// Credits: http://2ality.com/2018/05/child-process-streams.html
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const { spawn } = require('child_process')
/*** Step 1. Get lerna.json config ***/
const lernaConfig = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../lerna.json')))
/*** Step 2. Run npm install over all packages in order ***/
async function runChildProcess(childProcess) {
return new Promise((resolve, reject) => {
childProcess.once('exit', (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Exit with error code: ${code}`));
}
})
childProcess.once('error', (err) => {
reject(err);
})
})
}
let activeChildProcess
async function main() {
for (const pkgGlob of lernaConfig.packages) {
const pkgDirs = glob.sync(pkgGlob)
for (const pkgDir of pkgDirs) {
console.info(`Start installing package under ${pkgDir} ...`)
activeChildProcess = spawn(`npm install -C ${pkgDir}`, {
stdio: 'inherit',
shell: true
})
await runChildProcess(activeChildProcess);
}
}
activeChildProcess = null
}
main()
/*** Step 3. Attach main process listener ***/
process.on('SIGINT', () => {
// ctrl+c event
process.exit(1)
})
.on('exit', () => {
if (activeChildProcess) {
console.info('Stop active child processes...')
activeChildProcess.kill()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment