npm, of Node.js.
We start with a “Hello world” program. Save the following content in hello.js or other file name.
#!/usr/bin/env node "use strict"; console.log("Hello World!");
Execute the script with
node or add exec mode with
$ node hello.js Hello World!
Or do this:
$ chmod +x hello.js $ ./hello.js
If you want to install third-party libraries of Node.js, use
npm behaves a little different from the package manager of other programming language.
npm install libraries into the subdirectory of current directory called node_modules and
node search node_modules for libraries. If you change to different directories, you may need to re-install libraries. To install libraries to a fixed system directory, install Node.js packages with
npm install -g.
You also need to set NODE_PATH variable in shell config file like ~/.profile.
$ npm install -g readline-sync
Here is an example to use readline-sync
var readlineSync = require('readline-sync'); var answer = readlineSync.question('What is your favorite food? '); console.log('Oh, so your favorite food is ' + answer);
Using blocking I/O is not a good style in Node.js, but it's easier than writing callbacks just for inputs from yourself.
Node.js store command line arguments in process.argv array. To receive data from command line arguments, do like the following example:
var arg = process.argv.slice(2); // change console.log to other intended description console.log(arg);
We do no command line parsing here. We just receive data from first argument. If you need some command line parsing, you can use optimist.