Node by example: 4. Basics
Published on April 21, 2010
0 Comments
4. Basics
The complete source code can be downloaded here: http://github.com/Hendrik/node-by-example
Encodings:
Node.JS supports UTF-8 ("utf8"), ASCII ("ascii") and Binary ("binary").
ASCII and Binary are relatively fast, UTF-8 is slower and should be avoided when possible.
Globals: [1]
i) Arguments:
See 04_Basics/global.js:
var sys = require("sys"),
some_argument = process.argv[2];
// argument example
if (!some_argument) {
return sys.puts("Usage: node " + __filename.replace(__dirname + "/", "") + " some_argument");
}
// require example
sys.puts("Default require.paths: " + require.paths);
sys.puts("Adding current directory to require.paths");
require.paths.unshift(__dirname);
sys.puts("Modified require.paths: " + require.paths);
run it via
node global.js test_arg
The output will be something like:
Default require.paths: /root/.node_libraries Adding current directory to require.paths Modified require.paths: /usr/src/node-by-example/04_Basics,/root/.node_libraries
process.argv is an array containing the command line arguments.
some_argument = process.argv[2];
In this case "node" would be argv[0], "global.js" argv[1] and "test_arg" argv[2].
if (!some_argument) {
return sys.puts("Usage: node " + __filename.replace(__dirname + "/", "") + " some_argument");
}
If a command line argument is not provided, the script will output the correct usage, where __filename is the global object for the name of the currently executed file and __dirname is the name of the directory of the currently executed code.
ii) require
require.paths
provides the search path for absolute path arguments to require()
You can add a directory to the search path by unshifting the new directory to require.paths:
require.paths.unshift(__dirname); // adds the current directory to the search directory
Process: [2]
The process Object provides information about the currently running process, such as its process ID, the platform it is running on, memory usage, ...
You can exit a script by providing an exit code, e.g.:
process.exit(0);
By default it exits using success code 0. See 04_Basics/process.js:
var sys = require("sys");
// display all command line arguments
sys.puts("Provided arguments:");
for (var key in process.argv) {
sys.puts(key + ": " + process.argv[key]);
}
// process details (PID, platform, memory usage)
sys.puts("\nPID: " + process.pid);
sys.puts("Platform: " + process.platform);
sys.puts("Memory usage: " + process.memoryUsage().rss);
// display user environment
sys.puts("\nUser Environment:");
for (var key in process.env) {
sys.puts(key + ": " + process.env[key]);
}
// process exit code - default: success code 0
process.exit(0);
System module: [3]
The system module provides various ways to send output to the console.
sys.puts()
outputs the string with a trailing newline.
sys.print()
outputs the string without any newline.
sys.debug("Some debug output")
outputs the string preceeded by "DEBUG: ", e.g.:
DEBUG: Some debug output
sys.log("Some log output")
outputs the string preceeded by the current date & time, e.g.:
20 Mar 23:17:15 - Some log output
sys.inspect(process.memoryUsage())
outputs a string representation of the provided object, e.g.:
{ rss: 5263360
, vsize: 41353216
, heapTotal: 2176512
, heapUsed: 963872
}
See 04_Basics/sys.js:
var sys = require("sys");
// sys output examples
sys.puts("Output with trailing newline");
sys.print("Output without ");
sys.print("new line");
sys.puts("\nAdd newline to begining and extra one at the end.\n");
sys.debug("Some debug output");
sys.log("Some log output");
// simple sys.inspect example
var process_memory = process.memoryUsage();
sys.puts("\nprocess.memoryUsage():");
sys.puts(sys.inspect(process_memory));
Timers: [4]
You can use the JavaScript timers, such as setTimeout(), clearTimeout(), setInterval(), clearInterval() in your node apps.
See 04_Basics/timers.js:
var sys = require("sys");
// simple timout example - waits for 2sec before continuing with the next step
var start_time = new Date();
sys.puts("Starting 2 second timer");
setTimeout(function() {
var end_time = new Date();
var difference = end_time.getTime() - start_time.getTime();
sys.puts("Stopped timer after " + Math.round(difference/1000) + " seconds");
cleartimeout_example();
}, 2000);
// clearTimeout example - timout set for 30secs, gets cancelled via clearTimeout right away, no output
function cleartimeout_example() {
var start_time = new Date();
sys.puts("\nStarting 30 second timer and stopping it immediately without triggering callback");
var timeout = setTimeout(function() {
var end_time = new Date();
var difference = end_time.getTime() - start_time.getTime();
sys.puts("Stopped timer after " + Math.round(difference/1000) + " seconds");
}, 30000);
clearTimeout(timeout);
interval_example();
}
// interval example - 5x output every 2secs using setInterval
function interval_example() {
var start_time = new Date();
sys.puts("\nStarting 2 second interval, stopped after 5th tick");
var count = 1;
var interval = setInterval(function() {
if (count == 5) clearInterval(this);
var end_time = new Date();
var difference = end_time.getTime() - start_time.getTime();
sys.puts("Tick no. " + count + " after " + Math.round(difference/1000) + " seconds");
count++;
}, 2000);
}
[1] http://nodejs.org/api.html#global-objects-38
[2] http://nodejs.org/api.html#process-46
[3] http://nodejs.org/api.html#sys-68
[4] http://nodejs.org/api.html#timers-74
