I'd like to add a self-updating feature to a globally installed module. Is there a better way of doing it than this?
require("child_process").exec("npm update -g module-name");
There's some documentation about installing npm as a local dependency. Is this necessary? Is there any sample code on how to execute commands like update or install ?
Here's what I've usually done to use the system copy of npm instead of installing another copy of npm as a local module:
function loadNpm(cb) {
require('child_process').exec('npm', function(err, stdout, stderr) {
var m = /npm#[^ ]+ (.+)\n/i.exec(stdout);
if (!m)
return cb(new Error('Unable to find path in npm help message'));
cb(undefined, require(m[1]));
});
}
// usage ...
// only need to call `loadNpm()` once
loadNpm(function(err, npm) {
if (err) throw err;
// load() is required before using npm API
npm.load(function(err, npm) {
if (err) throw err;
// e.g. npm.search('ssh', true, function(err, results) { console.dir(results); });
});
});
Depending on your goals, here are a few options:
1) Via exec() as you mention. Don't forget to add an error callback.
2) Using the npm package as you mention.
For example, I wrote a quick script to install the Yeoman package globally which worked well. I didn't see a lot of documentation for this so I started reading the source code in the npm package itself.
var npm = require('npm');
npm.load (function (err, npm) {
if (err) {
console.log("Error loading");
return;
}
npm.config.set('global', true);
npm.commands.install(['yo'], function (err) {
if (err) {
console.error("Installation failed");
}
});
});
3) Another option is to just have a cron job auto-update packages if that is your goal.
4) You may also be interested in this package https://github.com/tjunnone/npm-check-updates
Related
It's not very well documented, but you can use npm as a Node.js module and call commands in the code.
I want to capture user input for what packages are required and installing them this way and also save them to the package with the --save-dev flag. I've tried to no avail to get this up and running in code, with it installing but can't find a way to get it to save to the package file.
Is this even possible, or would it have be done another way. Alternate methods are welcome and appreciated.
var npm = require("npm")
npm.load({}, function (er) {
if (er) return handlError(er)
npm.commands.install(["titlecase"], function (err, data) {
if (err) return console.error(err)
})
})
It is possible, flags need to be passed to npm.load():
var npm = require('npm');
npm.load({ 'save-dev': true }, function (err) {
if (err) console.log(err);
npm.commands.install(['lodash'], function (err, data) {
if (err) return console.error(err)
});
});
You have the list of flags and their type here.
I have a Meteor app that needs to call a python script to do some stuff in the background. How can I get this to work? I've tried using child_process and exec, but I can't seem to get it to execute properly. Where should the script even be located?
Thanks
I have same problems and its solved use python-sheel an npm packages to run Python scripts from Node.js
Install on meteor :
meteor npm install --save python-shell
There is simple usage :
var PythonShell = require('python-shell');
PythonShell.run('my_script.py', function (err) {
if (err) throw err;
console.log('finished');
});
If you want run with arguments and options :
var PythonShell = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'path/to/python',
pythonOptions: ['-u'],
scriptPath: 'path/to/my/scripts',
args: ['value1', 'value2', 'value3']
};
PythonShell.run('my_script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
here detail about python-shell https://github.com/extrabacon/python-shell
Thanks extrabacon :)
Can you configure other installation commands in yeoman, beyond the standards(bower, npm) that it can run on your self generator?
You are in full control of the generator you write, so there's nothing stopping you from executing any command you would like, including other installation tools.
If you take a look at the install.js file in yeoman-generator you'll see that runInstall (which is run by installDependencies, bowerInstall and npmInstall) just combines some arguments that are then executed by this.spawnCommand:
var args = ['install'].concat(paths).concat(dargs(options));
this.spawnCommand(installer, args, cb)
.on('error', cb)
.on('exit', this.emit.bind(this, installer + 'Install:end', paths))
.on('exit', function (err) {
if (err === 127) {
this.log.error('Could not find ' + installer + '. Please install with ' +
'`npm install -g ' + installer + '`.');
}
cb(err);
}.bind(this));
(Source)
If you want to run a custom tool to install dependencies, you can just define a function like this in your own generator.
Is there a way to execute a shell command when creating a grunt-init scaffolding template? For example I would like to execute "bower install" and "git init" after the project is created without having to enter the commands afterwards. The API does not seem to include this functionality.
The template.js is executed by node, so you can use anything node has to offer you.
I've managed to that with the child_process.exec:
var exec = require("child_process").exec;
...
exec("bower install", function(error, stdout, stderr) {
if (error !== null) {
console.log("Error: " + error);
}
done();
});
The only "problem" that I see is that you don't have any logs from bower, so if you are installing many components, it may take a while before any other visual feedback.
I have one node.js application published in appfog, but when I try to access a mysql database through javascript
with ( https://github.com/felixge/node-mysql ), "node-mysql" seems that is not installed, what is the way to do this?
there is no documentation on appfog site. thanks.
the code of server app.js:
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
var cre = env['mysql-5.1'][0]['credentials'];
}
var Client = require('mysql').Client,
client = new Client();
client.user = cre.user;
client.password = cre.password;
client.host=cre.host;
client.port=cre.port;
client.database=cre.name;
client.connect();
client.query(
'SELECT * FROM scores ',
function selectPlayers(err, results, fields) {
if (err) {
console.log("Error: " + err.message);
throw err;
}
console.log("Number of rows: "+results.length);
console.log(results);
client.end();
});
and the error:
module.js:340
throw err;
^
Error: Cannot find module 'mysql'
at Function.Module._resolveFilename (module.js:338:15)
you should add
"mysql": "2.0.x || 2.1.x",
to the dependencies in your package.json file, and then do
npm install
You can check out Appfog's documentation here. There is a section about dependency management
Appfog have support for NPM, the standard way to install dependencies in node.
You can either do it through the console with npm install mysql or by adding mysql to your package.json file and do npm install.
The second way will automatically install all the dependencies for your app.
Source: https://docs.appfog.com/languages/node#node-dep-mgmt
Hi you just need to download and install node.js locally this will enable npm command on your machine after that go to "Services" section on your AppFog panel create you mySQL service (VCAP_SERVICES)
When you provision and bind a service to your app, AppFog creates an environment variable called VCAP_SERVICES.
This variable contains a JSON document with a list of all credentials and connection information for the bound services.
Here's an example that of the environment variable for an app that has two MySQL database services bound to it:
{"mysql-5.1":[
{
"name":"mysql-4f700",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"d6d665aa69817406d8901cd145e05e3c6",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uB7CoL4Hxv9Ny",
"username":"uB7CoL4Hxv9Ny",
"password":"pzAx0iaOp2yKB"
}
},
{
"name":"mysql-f1a13",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"db777ab9da32047d99dd6cdae3aafebda",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uJHApvZF6JBqT",
"username":"uJHApvZF6JBqT",
"password":"p146KmfkqGYmi"
}
}
]}
You can use your app's language-specific facility to call the environment variable.
In Java:
java.lang.System.getenv("VCAP_SERVICES")
In Ruby:
ENV['VCAP_SERVICES']
In Javascript:
process.env.VCAP_SERVICES
In Python:
os.getenv("VCAP_SERVICES")
In PHP:
getenv("VCAP_SERVICES")