### 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