### Example process.execPath output Source: https://iojs.org/api/process.json Example output of process.execPath, which is the absolute pathname of the executable that started the process. ```bash /usr/local/bin/iojs ``` -------------------------------- ### Buffer index get and set example Source: https://iojs.org/api/buffer.json Shows how to get and set individual octets in a buffer using buf[index]. The example copies an ASCII string into a buffer one byte at a time and prints the buffer, with the output comment showing 'io.js'. ```javascript str = "io.js"; buf = new Buffer(str.length); for (var i = 0; i < str.length ; i++) { buf[i] = str.charCodeAt(i); } console.log(buf); // io.js ``` -------------------------------- ### Start REPLs on stdin, Unix socket, and TCP socket Source: https://iojs.org/api/repl.json This example starts a REPL on stdin, a Unix socket, and a TCP socket. It uses net.createServer to listen on a Unix socket and a TCP port. The REPL instances share the same global object but have unique I/O. Use telnet for TCP connections and socat for Unix or TCP connections. ```javascript var net = require('net'), repl = require('repl'), connections = 0; repl.start({ prompt: "io.js via stdin> ", input: process.stdin, output: process.stdout }); net.createServer(function (socket) { connections += 1; repl.start({ prompt: "io.js via Unix socket> ", input: socket, output: socket }).on('exit', function() { socket.end(); }) }).listen("/tmp/iojs-repl-sock"); net.createServer(function (socket) { connections += 1; repl.start({ prompt: "io.js via TCP socket> ", input: socket, output: socket }).on('exit', function() { socket.end(); }); }).listen(5001); ``` -------------------------------- ### Running the cluster example with NODE_DEBUG Source: https://iojs.org/api/cluster.json Command to run the cluster example with debug output, showing the master and workers coming online. ```bash % NODE_DEBUG=cluster iojs server.js 23521,Master Worker 23524 online 23521,Master Worker 23526 online 23521,Master Worker 23523 online 23521,Master Worker 23528 online ``` -------------------------------- ### Circular require() example - a.js Source: https://iojs.org/api/modules.json Part of a three-file example demonstrating circular dependencies. a.js starts, sets exports.done to false, requires b.js, logs b.done, then sets exports.done to true. ```javascript console.log('a starting'); exports.done = false; var b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done'); ``` -------------------------------- ### Tiny CLI example using readline Source: https://iojs.org/api/readline.json Complete example of a tiny command line interface using readline. It creates an interface, sets a prompt, handles 'line' events with a switch on trimmed input, and exits on 'close'. ```javascript var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout); rl.setPrompt('OHAI> '); rl.prompt(); rl.on('line', function(line) { switch(line.trim()) { case 'hello': console.log('world!'); break; default: console.log('Say what? I might have heard `' + line.trim() + '`'); break; } rl.prompt(); }).on('close', function() { console.log('Have a great day!'); process.exit(0); }); ``` -------------------------------- ### dns.lookup options object example Source: https://iojs.org/api/dns.json Shows an example options object for dns.lookup, with family, hints, and all properties. All properties are optional; family must be 4 or 6, hints can be one or more getaddrinfo flags ORed together, and all defaults to false. ```javascript { family: 4, hints: dns.ADDRCONFIG | dns.V4MAPPED, all: false } ``` -------------------------------- ### Circular require() example - main.js Source: https://iojs.org/api/modules.json Entry point for the circular dependency example. Loads a.js and b.js, then logs the final values of their exports. ```javascript console.log('main starting'); var a = require('./a.js'); var b = require('./b.js'); console.log('in main, a.done=%j, b.done=%j', a.done, b.done); ``` -------------------------------- ### binding.gyp configuration for a single addon source file Source: https://iojs.org/api/addons.json Create this binding.gyp file to compile the addon examples with node-gyp. The sources array lists the .cc files that make up the addon. This example uses a single source file named addon.cc. ```json { "targets": [ { "target_name": "addon", "sources": [ "addon.cc" ] } ] } ``` -------------------------------- ### path.relative examples Source: https://iojs.org/api/path.json Examples for path.relative solving the relative path from 'from' to 'to'. If either argument is a zero-length string, the current working directory is used instead. If both paths are the same, a zero-length string is returned. ```javascript path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') // returns '..\\..\\impl\\bbb' path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') // returns '../../impl/bbb' ``` -------------------------------- ### Output of circular require() example Source: https://iojs.org/api/modules.json Expected output when running 'iojs main.js' for the circular dependency example. Shows the order of execution and the values of exports at each step. ```bash $ iojs main.js main starting a starting b starting in b, a.done = false b done in a, b.done = true a done in main, a.done=true, b.done=true ``` -------------------------------- ### path.isAbsolute Windows examples Source: https://iojs.org/api/path.json Windows examples for path.isAbsolute. An absolute path always resolves to the same location regardless of the working directory. If the path string is zero-length, it is used as-is and false is returned. ```javascript path.isAbsolute('//server') // true path.isAbsolute('C:/foo/..') // true path.isAbsolute('bar\\baz') // false path.isAbsolute('.') // false ``` -------------------------------- ### Basic cluster example with HTTP server Source: https://iojs.org/api/cluster.json Creates a cluster of workers that share port 8000. The master forks a worker for each CPU, and workers create an HTTP server. The example logs worker deaths and uses the 'exit' event. ```javascript var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer(function(req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); } ``` -------------------------------- ### domain.bind(callback) Example Source: https://iojs.org/api/domain.json Shows how to use domain.bind to wrap a callback so that any errors thrown inside it are routed to the domain's 'error' event. The example reads a file and parses JSON, with the bound callback ensuring errors are caught by the domain. ```javascript var d = domain.create(); function readSomeFile(filename, cb) { fs.readFile(filename, 'utf8', d.bind(function(er, data) { // if this throws, it will also be passed to the domain return cb(er, data ? JSON.parse(data) : null); })); } d.on('error', function(er) { // an error occurred somewhere. // if we throw it now, it will crash the program // with the normal line number and stack message. }); ``` -------------------------------- ### repl.start(options) Source: https://iojs.org/api/repl.json Returns and starts a REPLServer instance. Accepts an options object to configure the REPL's prompt, streams, evaluation function, and behavior. ```APIDOC ## [START] repl.start(options) ### Description Returns and starts a REPLServer instance that inherits from Readline Interface. Accepts an options object with configuration values for prompt, streams, terminal behavior, evaluation, and more. ### Method START ### Endpoint repl.start(options) ### Parameters #### Options Object - **prompt** (string) - Optional - The prompt and stream for all I/O. Defaults to `> `. - **input** (Readable) - Optional - The readable stream to listen to. Defaults to `process.stdin`. - **output** (Writable) - Optional - The writable stream to write readline data to. Defaults to `process.stdout`. - **terminal** (boolean) - Optional - Pass `true` if the stream should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY` on the `output` stream upon instantiation. - **eval** (function) - Optional - Function that will be used to eval each given line. Defaults to an async wrapper for `eval()`. The function should have the signature: `function eval(cmd, context, filename, callback) { callback(null, result); }`. On tab completion, `eval` will be called with `.scope` as an input string and is expected to return an array of scope names for auto-completion. - **useColors** (boolean) - Optional - Whether the `writer` function should output colors. Defaults to the repl's `terminal` value. - **useGlobal** (boolean) - Optional - If `true`, the repl uses the `global` object instead of a separate context. Defaults to `false`. - **ignoreUndefined** (boolean) - Optional - If `true`, the repl will not output the return value of a command if it's `undefined`. Defaults to `false`. - **writer** (function) - Optional - The function to invoke for each command that gets evaluated which returns the formatting (including coloring) to display. Defaults to `util.inspect`. - **replMode** (string) - Optional - Controls whether the repl runs all commands in strict mode, default mode, or a hybrid mode. Acceptable values: repl.REPL_MODE_SLOPPY, repl.REPL_MODE_STRICT, repl.REPL_MODE_MAGIC. ### Returns Returns and starts a REPLServer instance, that inherits from [Readline Interface][]. ### Example ```js var net = require('net'), repl = require('repl'), connections = 0; repl.start({ prompt: "io.js via stdin> ", input: process.stdin, output: process.stdout }); net.createServer(function (socket) { connections += 1; repl.start({ prompt: "io.js via Unix socket> ", input: socket, output: socket }); }); ``` -------------------------------- ### HTTP server example Source: https://iojs.org/api/synopsis.json Creates an HTTP server that responds with 'Hello World' on port 8124. Run by saving to example.js and executing with iojs. ```javascript var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); ``` ```shell > iojs example.js Server running at http://127.0.0.1:8124/ ``` -------------------------------- ### myobject.cc: Implement MyObject constructor, Init, New, and NewInstance Source: https://iojs.org/api/addons.json Implements MyObject. Init prepares the constructor template, New handles both construct and plain function calls, and NewInstance creates instances for the addon. ```cpp // myobject.cc #include #include "myobject.h" namespace demo { using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Isolate* isolate) { // Prepare constructor template Local tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); constructor.Reset(isolate, tpl->GetFunction()); } void MyObject::New(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local argv[argc] = { args[0] }; Local cons = Local::New(isolate, constructor); args.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } void MyObject::NewInstance(const FunctionCallbackInfo& args) { Isolate* isolate = args.GetIsolate(); const unsigned argc = 1; Local argv[argc] = { args[0] }; Local cons = Local::New(isolate, constructor); Local instance = cons->NewInstance(argc, argv); args.GetReturnValue().Set(instance); } } // namespace demo ``` -------------------------------- ### Circular require() example - b.js Source: https://iojs.org/api/modules.json Part of a three-file example demonstrating circular dependencies. b.js starts, sets exports.done to false, requires a.js, logs a.done, then sets exports.done to true. ```javascript console.log('b starting'); exports.done = false; var a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done'); ``` -------------------------------- ### server.listen(options[, callback]) Source: https://iojs.org/api/net.json Starts a server listening for connections using the specified options. Supports port, host, backlog, path, and exclusive properties, with an optional callback. ```APIDOC ## server.listen(options[, callback]) ### Description Starts a server listening for connections. The `port`, `host`, and `backlog` properties of `options` behave as in `server.listen(port, [host], [backlog], [callback])`. Alternatively, the `path` option can specify a UNIX socket. If `exclusive` is `false` (default), cluster workers share the underlying handle; if `true`, the handle is not shared and port sharing results in an error. ### Method listen ### Parameters #### options (Object) - Required - **port** (Number) - Optional - The port to listen on. - **host** (String) - Optional - The hostname or IP address. - **backlog** (Number) - Optional - The maximum length of the queue of pending connections. - **path** (String) - Optional - The path for a UNIX socket. - **exclusive** (Boolean) - Optional - If true, do not share the handle with cluster workers. #### callback (Function) - Optional Called when the server is listening. ### Request Example ```javascript server.listen({ host: 'localhost', port: 80, exclusive: true }); ``` ### Response No response body. The callback is invoked when listening starts. ``` -------------------------------- ### server.listen(options[, callback]) Source: https://iojs.org/api/net.json Starts a server listening with the specified options (port, host, backlog, path). Asynchronous; emits 'listening' event when bound. ```APIDOC ## server.listen(options[, callback]) ### Description Starts a server listening with the specified options. This function is asynchronous; when the server has been bound, the 'listening' event will be emitted. The last parameter callback will be added as a listener for the 'listening' event. ### Parameters - **options** (Object) - Required - Supports the following properties: - **port** (Number) - Optional - Port number. - **host** (String) - Optional - Host name. - **backlog** (Number) - Optional - Backlog size. - **path** (String) - Optional - Path for local domain. - **callback** (Function) - Optional - Listener for the 'listening' event. ``` -------------------------------- ### http.get() example Source: https://iojs.org/api/http.json Use this convenience method for GET requests without bodies. It sets the method to GET and calls req.end() automatically, differing from http.request() only in that respect. The callback receives the response object, and errors are handled via the 'error' event. ```javascript http.get("http://www.google.com/index.html", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); ``` -------------------------------- ### Buffer.byteLength example Source: https://iojs.org/api/buffer.json Shows how to get the byte length of a string with default utf8 encoding. The result differs from String.prototype.length because it counts bytes, not characters. ```javascript str = '\u00bd + \u00bc = \u00be'; ``` -------------------------------- ### repl.start(options) Source: https://iojs.org/api/repl.json Starts a REPL instance with the given options. This method is used to embed a REPL in other programs or to customize the REPL's behavior. ```APIDOC ## repl.start(options) ### Description Starts a REPL instance with the given options. This method is used to embed a REPL in other programs or to customize the REPL's behavior. ### Method start ### Parameters #### options (Object) - Optional - An object containing options for the REPL. ### Response Returns a REPL instance. ``` -------------------------------- ### Listening for 'reset' event in REPL Source: https://iojs.org/api/repl.json Emitted when the REPL's context is reset, which happens when you type .clear. If you start the repl with { useGlobal: true } then this event will never be emitted. Example of listening for reset. ```javascript // Extend the initial repl context. r.on('reset', function (context) { console.log('Got "reset" event from repl!'); }); ``` -------------------------------- ### server.listen(port[, hostname][, backlog][, callback]) Source: https://iojs.org/api/net.json Starts accepting connections on the specified port and hostname. ```APIDOC ## server.listen(port[, hostname][, backlog][, callback]) ### Description Begin accepting connections on the specified port and hostname. If hostname is omitted, the server accepts connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A port value of zero assigns a random port. Backlog is the maximum length of the queue of pending connections. This function is asynchronous; when the server has been bound, the 'listening' event is emitted. The callback is added as a listener for the 'listening' event. ### Method listen ### Parameters - **port** (Number) - Required - The port to listen on. - **hostname** (String) - Optional - The hostname to bind to. - **backlog** (Number) - Optional - Maximum length of the queue of pending connections. Default is 511. - **callback** (Function) - Optional - Listener for the 'listening' event. ### Events - 'listening' - Emitted when the server has been bound. - 'error' - Emitted on error, e.g., EADDRINUSE. ``` -------------------------------- ### Workaround with socket.resume() Source: https://iojs.org/api/stream.json Workaround for the broken example: call socket.resume() to start the flow of data and discard it, allowing the 'end' event to fire. This is the recommended fix for the edge case where no 'data' handler, resume(), or pipe is used. ```javascript // Workaround net.createServer(function(socket) { socket.on('end', function() { socket.end('I got your message (but didnt read it)\n'); }); // start the flow of data, discarding it. socket.resume(); }).listen(1337); ``` -------------------------------- ### path.format() example Source: https://iojs.org/api/path.json Example of path.format() returning a path string from an object, the opposite of path.parse(). ```javascript path.format({ root : "/", dir : "/home/user/dir", base : "file.txt", ext : ".txt", name : "file" }) // returns '/home/user/dir/file.txt' ``` -------------------------------- ### path.dirname example Source: https://iojs.org/api/path.json Example for path.dirname returning the directory name of a path, similar to the Unix dirname command. ```javascript path.dirname('/foo/bar/baz/asdf/quux') // returns '/foo/bar/baz/asdf' ``` -------------------------------- ### buf.slice([start][, end]) Source: https://iojs.org/api/buffer.json Returns a new buffer that references the same memory as the old, but offset and cropped by the start and end indexes. Negative indexes start from the end of the buffer, and modifying the new buffer slice will modify memory in the original buffer. ```APIDOC ## buf.slice([start][, end]) ### Description Returns a new buffer which references the same memory as the old, but offset and cropped by the `start` (defaults to `0`) and `end` (defaults to `buffer.length`) indexes. Negative indexes start from the end of the buffer. **Modifying the new buffer slice will modify memory in the original buffer!** ### Method slice ### Parameters - **start** (Number) - Optional, Default: 0 - **end** (Number) - Optional, Default: `buffer.length` ### Example ```javascript var buf1 = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a } var buf2 = buf1.slice(0, 3); console.log(buf2.toString('ascii', 0, buf2.length)); buf1[0] = 33; console.log(buf2.toString('ascii', 0, buf2.length)); // abc // !bc ``` ``` -------------------------------- ### server.listen(path[, callback]) Source: https://iojs.org/api/net.json Starts accepting connections on a Unix socket path. ```APIDOC ## server.listen(path[, callback]) ### Description Begin accepting connections on the specified Unix socket path. The callback is added as a listener for the 'listening' event. ### Method listen ### Parameters - **path** (String) - Required - The Unix socket path. - **callback** (Function) - Optional - Listener for the 'listening' event. ``` -------------------------------- ### Worker 'disconnect' event example Source: https://iojs.org/api/cluster.json Example for the 'disconnect' event on a worker. Attaches a 'disconnect' listener to a forked worker. ```javascript cluster.fork().on('disconnect', function() { // Worker has disconnected }); ``` -------------------------------- ### response.writeHead() example with Content-Length and Content-Type Source: https://iojs.org/api/http.json Example for response.writeHead() showing how to send a response header with a status code and headers. The Content-Length is given in bytes, not characters; this example works because 'hello world' contains only single-byte characters. For higher-coded characters, use Buffer.byteLength() to determine the byte length. ```javascript var body = 'hello world'; response.writeHead(200, { 'Content-Length': body.length, 'Content-Type': 'text/plain' }); ``` -------------------------------- ### process.execArgv vs process.argv example Source: https://iojs.org/api/process.json Shows that process.execArgv contains only io.js-specific command line options (here '--harmony'), while process.argv contains the executable path, script name, and options after the script name. ```bash $ iojs --harmony script.js --version ``` ```javascript ['--harmony'] ``` ```javascript ['/usr/local/bin/iojs', 'script.js', '--version'] ``` -------------------------------- ### new vm.Script(code, options) Source: https://iojs.org/api/vm.json Creates a new Script instance for holding precompiled scripts, and running them in specific sandboxes. ```APIDOC ## new vm.Script(code, options) ### Description A class for holding precompiled scripts, and running them in specific sandboxes. ### Parameters - **code** (string) - Required - The JavaScript code to compile. - **options** (object) - Required - Options for the script compilation. ### Notes This is a constructor for the Script class. ``` -------------------------------- ### buf.toString([encoding][, start][, end]) Source: https://iojs.org/api/buffer.json Decodes and returns a string from buffer data using the specified encoding, with optional start and end indices. ```APIDOC ## buf.toString([encoding][, start][, end]) ### Description Decodes and returns a string from buffer data encoded using the specified character set encoding. If `encoding` is `undefined` or `null`, then `encoding` defaults to `'utf8'`. The `start` and `end` parameters default to `0` and `buffer.length` when `undefined`. ### Method Method (instance method) ### Endpoint `buf.toString([encoding][, start][, end])` ### Parameters - `encoding` (String) - Optional, Default: 'utf8' - Character set encoding to use for decoding. - `start` (Number) - Optional, Default: 0 - Starting index for decoding. - `end` (Number) - Optional, Default: `buffer.length` - Ending index for decoding. ### Request Example ```javascript buf = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf[i] = i + 97; // 97 is ASCII a } buf.toString('ascii'); // outputs: abcdefghijklmnopqrstuvwxyz buf.toString('ascii',0,5); // outputs: abcde buf.toString('utf8',0,5); // outputs: abcde buf.toString(undefined,0,5); // encoding defaults to 'utf8', outputs abcde ``` ### Response Returns a string decoded from the buffer data. ``` -------------------------------- ### spawn(command[, args][, options]) Source: https://iojs.org/api/child_process.json Documents the child_process.spawn method for launching a new process with command line arguments and options. ```APIDOC ## [SPAWN] [child_process.spawn(command[, args][, options])] ### Description Launches a new process with the given command and command line arguments in args. If omitted, args defaults to an empty Array. Additional options can be specified as the third argument, with defaults of { cwd: undefined, env: process.env }. ### Method spawn ### Endpoint child_process.spawn(command[, args][, options]) ### Parameters #### Path Parameters - **command** (string) - Required - The command to run. - **args** (Array) - Optional - List of string arguments. Defaults to empty Array. - **options** (Object) - Optional - Additional options, with defaults { cwd: undefined, env: process.env }. #### Options - **cwd** (string) - Optional - Working directory from which the process is spawned. If not given, inherits current working directory. - **env** (Object) - Optional - Environment variables visible to the new process. Default is process.env. ### Request Example ```javascript var spawn = require('child_process').spawn, ls = spawn('ls', ['-lh', '/usr']); ``` ### Response #### Success Response No formal response object; the method returns a ChildProcess object with stdout, stderr, and event handlers. #### Response Example ```javascript ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('close', function (code) { console.log('child process exited with code ' + code); }); ``` ``` -------------------------------- ### Worker 'online' event example Source: https://iojs.org/api/cluster.json Example for the 'online' event on a worker. Attaches an 'online' listener to a forked worker. Note: this event is not emitted in the worker. ```javascript cluster.fork().on('online', function() { // Worker is online }); ``` -------------------------------- ### http.get(options[, callback]) Source: https://iojs.org/api/http.json Convenience method for making GET requests. It sets the method to GET and calls req.end() automatically, differing from http.request() only in these aspects. ```APIDOC ## [GET] http.get(options[, callback]) ### Description Since most requests are GET requests without bodies, io.js provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically. ### Method GET ### Endpoint http.get(options[, callback]) ### Parameters #### Path Parameters - **options** (object) - Required - Options for the HTTP request - **callback** (function) - Optional - Callback function invoked with the response ### Request Example http.get("http://www.google.com/index.html", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); ### Response #### Success Response - **res** (http.IncomingMessage) - The response object containing statusCode and other response properties #### Response Example { "statusCode": 200 } ``` -------------------------------- ### Main addon module addon.cc Source: https://iojs.org/api/addons.json Defines the addon entry point that initializes the MyObject wrapper and registers it with NODE_MODULE. ```cpp // addon.cc #include #include "myobject.h" namespace demo { using v8::Local; using v8::Object; void InitAll(Local exports) { MyObject::Init(exports); } NODE_MODULE(addon, InitAll) } // namespace demo ``` -------------------------------- ### vm.runInNewContext(code[, sandbox][, options]) Source: https://iojs.org/api/vm.json Compiles code, contextifies the sandbox if passed or creates a new contextified sandbox if omitted, and runs the code with the sandbox as the global object, returning the result. ```APIDOC ## vm.runInNewContext(code[, sandbox][, options]) ### Description Compiles `code`, contextifies `sandbox` if passed or creates a new contextified sandbox if it's omitted, and then runs the code with the sandbox as the global object and returns the result. ### Parameters - **code** (string) - Required - The JavaScript code to compile and run. - **sandbox** (object) - Optional - The sandbox to contextify and use as the global object. - **options** (object) - Optional - Same options as `vm.runInThisContext`. ### Example ```javascript var util = require('util'); var vm = require('vm'); var sandbox = { animal: 'cat', count: 2 }; vm.runInNewContext('count += 1; name = "kitty"', sandbox); console.log(util.inspect(sandbox)); // { animal: 'cat', count: 3, name: 'kitty' } ``` ### Notes Running untrusted code is a tricky business requiring great care. `vm.runInNewContext` is quite useful, but safely running untrusted code requires a separate process. ``` -------------------------------- ### path.extname examples Source: https://iojs.org/api/path.json Examples for path.extname returning the extension from the last '.' to the end of the string in the last portion of the path. Returns an empty string if there is no '.' or if the first character is '.'. ```javascript path.extname('index.html') // returns '.html' path.extname('index.coffee.md') // returns '.md' path.extname('index.') // returns '.' path.extname('index') // returns '' path.extname('.index') // returns '' ``` -------------------------------- ### Print process.argv with forEach and example output Source: https://iojs.org/api/process.json Prints each element of process.argv with its index. The command and output show that the first element is 'iojs', the second is the script filename, and the rest are additional arguments. ```javascript // print process.argv process.argv.forEach(function(val, index, array) { console.log(index + ': ' + val); }); ``` ```bash $ iojs process-2.js one two=three four 0: iojs 1: /Users/mjr/work/iojs/process-2.js 2: one 3: two=three 4: four ``` -------------------------------- ### path.basename examples Source: https://iojs.org/api/path.json Examples for path.basename returning the last portion of a path, similar to the Unix basename command. The optional ext argument removes the extension if it matches. ```javascript path.basename('/foo/bar/baz/asdf/quux.html') // returns 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html') // returns 'quux' ``` -------------------------------- ### os.uptime() Source: https://iojs.org/api/os.json Returns the system uptime in seconds. ```APIDOC ## os.uptime() ### Description Returns the system uptime in seconds. ### Method os.uptime() ### Parameters None. ### Returns Number - The system uptime in seconds. ``` -------------------------------- ### Start debugger with iojs debug myscript.js Source: https://iojs.org/api/debugger.json Shows the initial output when starting the debugger on a script. The debugger listens on port 5858 and breaks at the first line. ```text % iojs debug myscript.js < debugger listening on port 5858 connecting... ok break in /home/indutny/Code/git/indutny/myscript.js:1 1 x = 5; 2 setTimeout(function () { 3 debugger; debug> ``` -------------------------------- ### server.listen(port[, hostname][, callback]) Source: https://iojs.org/api/tls.json Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A port value of zero will assign a random port. This function is asynchronous. The last parameter callback will be called when the server has been bound. ```APIDOC ## server.listen(port[, hostname][, callback]) ### Description Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. A port value of zero will assign a random port. This function is asynchronous. The last parameter callback will be called when the server has been bound. ### Method listen ### Parameters - **port** (number) - Required - The port to listen on. - **hostname** (string) - Optional - The hostname to bind to. - **callback** (Function) - Optional - Callback called when the server has been bound. ### Notes - See net.Server for more information. ``` -------------------------------- ### Start io.js REPL and evaluate JavaScript Source: https://iojs.org/api/repl.json Shows the interactive REPL session when running `iojs` without arguments. The output demonstrates evaluating an array assignment and a forEach loop, with the REPL printing results and the `...` continuation prompt. ```bash mjr:~$ iojs Type '.help' for options. > a = [ 1, 2, 3]; [ 1, 2, 3 ] > a.forEach(function (v) { ... console.log(v); ... }); 1 2 3 ``` -------------------------------- ### Worker 'listening' event example Source: https://iojs.org/api/cluster.json Example for the 'listening' event on a worker. Attaches a 'listening' listener to a forked worker, receiving the address. Note: this event is not emitted in the worker. ```javascript cluster.fork().on('listening', function(address) { // Worker is listening }); ``` -------------------------------- ### util.isString(object) example Source: https://iojs.org/api/util.json Returns true if the given object is a String, false otherwise. The example shows calls with an empty string, a string literal, a String object, and a number. ```JavaScript var util = require('util'); util.isString('') // true util.isString('foo') // true util.isString(String('foo')) // true util.isString(5) // false ```