Skip to content

Instantly share code, notes, and snippets.

@luveti
Last active May 17, 2017 20:47
Show Gist options
  • Save luveti/67a1c93be3d58b085f6c76ae876c556c to your computer and use it in GitHub Desktop.
Save luveti/67a1c93be3d58b085f6c76ae876c556c to your computer and use it in GitHub Desktop.
Installs node_modules into temp directory and gives you access to them. This lets you avoid needing a node_modules folder.
function installDeps(deps, quiet, cb) {
const hash = require('crypto').createHash('md5').update(__filename).digest('hex')
const dir = require('os').tmpdir() + require('path').sep + hash
try {
require('fs').mkdirSync(dir)
if (!quiet) console.log(`Created temp folder at "${dir}"`)
} catch (e) {}
try {
require('fs').writeFileSync(dir + require('path').sep + 'package.json', JSON.stringify({
name: hash, description: hash, author: hash, repository: hash, license: "ISC",
dependencies: deps.reduce((p, c) => { p[c]='latest'; return p; }, {})
}))
if (!quiet) console.log("Created package.json")
} catch (e) {}
if (!quiet) console.log("Ensuring dependencies are installed")
require('child_process').execSync(`cd ${dir} && npm install`)
cb.apply(undefined, deps.map(d => require(`${dir}/node_modules/${d}`.replace(/\\/g,'/'))))
}
/* Example
installDeps(['request', 'cheerio'], false, (request, cheerio) => {})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment