Can I install a NPM package from a javascript file running in Node.js? For example, I'd like to have a script, let's call it "script.js" that somehow (...using NPM or not...) install a package usually available through NPM. In this example, I'd like to install "FFI". (npm install ffi)
It's possible to use npm programmatically, as stated in the documentation. Here's the code example they provide:
var npm = require("npm");
npm.load(myConfigObject, function (er) {
if (er) return handlError(er);
npm.commands.install(["some", "args"], function (er, data) {
if (er) return commandFailed(er)
// command succeeded, and data might have some info
});
npm.on("log", function (message) { .... })
});
Since npm is in the node_modules folder, you can use require('npm') like any other module. In your case you specifically will be looking at the npm.commands.install() method:
If you need to look in the source then it's also on GitHub. Here's a complete working example of the code, where there are no options to pass:
var npm = require("npm");
npm.load(function (err) {
// catch errors
npm.commands.install(["ffi"], function (er, data) {
// log the error or data
});
npm.on("log", function (message) {
// log the progress of the installation
console.log(message);
});
});
Note that the first argument to the install function is an array. Each element of the array is a module that npm will attempt to install.
yes. you can use child_process to execute a system command
var exec = require('child_process').exec,
child;
child = exec('npm install ffi',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
it can actually be a bit easy
var exec = require('child_process').exec;
child = exec('npm install ffi').stderr.pipe(process.stderr);