### Example process.execPath Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows an example absolute pathname of the executable that started the process. ```bash /usr/local/bin/node ``` -------------------------------- ### Starting REPLs on stdin, Unix socket, and TCP socket Source: https://nodejs.org/docs/v0.6.14/api/all.html Example that starts a REPL on stdin, a Unix socket, and a TCP socket using repl.start. Demonstrates multiple REPLs sharing the same global object. ```javascript var net = require("net"), repl = require("repl"); connections = 0; repl.start("node via stdin> "); net.createServer(function (socket) { connections += 1; repl.start("node via Unix socket> ", socket); }).listen("/tmp/node-repl-sock"); net.createServer(function (socket) { connections += 1; repl.start("node via TCP socket> ", socket); }).listen(5001); ``` -------------------------------- ### http.get example with options and callback Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows how to make a GET request using http.get with an options object and a callback that logs the response status code. Also attaches an error handler to log any errors. ```javascript var options = { host: 'www.google.com', port: 80, path: '/index.html' }; http.get(options, function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); ``` -------------------------------- ### Output of process.versions example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example output showing the structure of the versions object. ```text { node: '0.4.12', v8: '3.1.8.26', ares: '1.7.4', ev: '4.4', openssl: '1.0.0e-fips' } ``` -------------------------------- ### path.relative examples Source: https://nodejs.org/docs/v0.6.14/api/all.html Solves the relative path from one absolute path to another. Examples show both Windows and POSIX style paths. ```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' ``` -------------------------------- ### Example output of process.argv script Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the output when running the process.argv example with the command 'node process-2.js one two=three four'. The output lists each argument with its index. ```bash $ node process-2.js one two=three four 0: node 1: /Users/mjr/work/node/process-2.js 2: one 3: two=three 4: four ``` -------------------------------- ### Zlib: HTTP client request example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example from the Zlib module documentation. It shows how to make an HTTP request with accept-encoding header and decompress the response based on content-encoding. ```javascript // client request example var zlib = require('zlib'); var http = require('http'); var fs = require('fs'); var request = http.get({ host: 'izs.me', path: '/', port: 80, headers: { 'accept-encoding': 'gzip,deflate' } }); request.on('response', function(response) { var output = fs.createWriteStream('izs.me_index.html'); switch (response.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases case 'gzip': response.pipe(zlib.createGunzip()).pipe(output); break; case 'deflate': response.pipe(zlib.createInflate()).pipe(output); break; default: response.pipe(output); break; } }); ``` -------------------------------- ### Zlib: HTTP server example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example from the Zlib module documentation. It shows how to create an HTTP server that compresses responses based on the accept-encoding header. Note that this is not a conformant accept-encoding parser. ```javascript // server example // Running a gzip operation on every request is quite expensive. // It would be much more efficient to cache the compressed buffer. var zlib = require('zlib'); var http = require('http'); var fs = require('fs'); http.createServer(function(request, response) { var raw = fs.createReadStream('index.html'); var acceptEncoding = request.headers['accept-encoding']; if (!acceptEncoding) { acceptEncoding = ''; } // Note: this is not a conformant accept-encoding parser. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 if (acceptEncoding.match(/\bdeflate\b/)) { response.writeHead(200, { 'content-encoding': 'deflate' }); raw.pipe(zlib.createDeflate()).pipe(response); } else if (acceptEncoding.match(/\bgzip\b/)) { response.writeHead(200, { 'content-encoding': 'gzip' }); raw.pipe(zlib.createGzip()).pipe(response); } else { response.writeHead(200, {}); raw.pipe(response); } }).listen(1337); ``` -------------------------------- ### Exposing a variable to the REPL via context Source: https://nodejs.org/docs/v0.6.14/api/all.html Example file repl_test.js that starts a REPL and assigns a variable to the context object so it appears as local within the REPL. ```javascript // repl_test.js var repl = require("repl"), msg = "message"; repl.start().context.m = msg; ``` -------------------------------- ### Spawn a child process and print its PID Source: https://nodejs.org/docs/v0.6.14/api/all.html Uses child_process.spawn() to start a grep process and logs the child's PID. The example ends the child's stdin, which often causes the child to terminate. ```javascript var spawn = require('child_process').spawn, grep = spawn('grep', ['ssh']); console.log('Spawned child pid: ' + grep.pid); grep.stdin.end(); ``` -------------------------------- ### writeUInt32BE and writeUInt32LE example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example showing how to write a 32-bit unsigned integer to a buffer in big-endian and little-endian formats. The output comments show the resulting buffer contents. ```javascript var buf = new Buffer(4); buf.writeUInt32BE(0xfeedface, 0); console.log(buf); buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // // ``` -------------------------------- ### Example options to reduce deflate memory to 128K Source: https://nodejs.org/docs/v0.6.14/api/all.html Example options object to reduce default memory from 256K to 128K. This will generally degrade compression. ```javascript { windowBits: 14, memLevel: 7 } ``` -------------------------------- ### querystring.stringify examples Source: https://nodejs.org/docs/v0.6.14/api/all.html Examples of serializing an object to a query string using default and custom separators and assignment characters. ```javascript querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }) // returns 'foo=bar&baz=qux&baz=quux&corge=' ``` ```javascript querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':') // returns 'foo:bar;baz:qux' ``` -------------------------------- ### request.url value for the example request Source: https://nodejs.org/docs/v0.6.14/api/all.html The value of request.url for the example HTTP request above. It contains only the URL path and query string. ```text '/status?name=ryan' ``` -------------------------------- ### writeFloatBE and writeFloatLE example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example showing how to write a 32-bit float to a buffer in big-endian and little-endian formats. The output comments show the resulting buffer contents. ```javascript var buf = new Buffer(4); buf.writeFloatBE(0xcafebabe, 0); console.log(buf); buf.writeFloatLE(0xcafebabe, 0); console.log(buf); // // ``` -------------------------------- ### server.listen(port, [hostname], [callback]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Starts the server listening on the specified port and optional hostname. The callback is invoked when the server is bound. ```APIDOC ## server.listen(port, [hostname], [callback]) ### Description Starts the server listening on the specified port and optional hostname. The callback is invoked when the server is bound. ### Parameters - **port** (number) - Required - The port number to listen on. - **hostname** (string) - Optional - The hostname to bind to. If omitted, the server accepts connections on any IPv4 address. - **callback** (function) - Optional - Callback function invoked when the server is listening. ### Example ```js server.listen(8080, '127.0.0.1', function() { console.log('Server listening on port 8080'); }); ``` ``` -------------------------------- ### server.listen(path, [callback]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Starts the server listening on the specified Unix socket path. The callback is invoked when the server is bound. ```APIDOC ## server.listen(path, [callback]) ### Description Starts the server listening on the specified Unix socket path. The callback is invoked when the server is bound. ### Parameters - **path** (string) - Required - The file path of the Unix socket. - **callback** (function) - Optional - Callback function invoked when the server is listening. ### Example ```js server.listen('/tmp/node.sock', function() { console.log('Server listening on socket'); }); ``` ``` -------------------------------- ### Log __dirname example Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the directory of the currently executing script when running node example.js from /Users/mjr. ```javascript console.log(__dirname); // /Users/mjr ``` -------------------------------- ### path.join examples Source: https://nodejs.org/docs/v0.6.14/api/all.html Joins all arguments together and normalizes the resulting path. Non-string arguments are ignored. ```javascript path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') // returns '/foo/bar/baz/asdf' path.join('foo', {}, 'bar') // returns 'foo/bar' ``` -------------------------------- ### Ask a question with rl.question Source: https://nodejs.org/docs/v0.6.14/api/all.html Example usage of the question method to prompt the user and handle the response. ```javascript interface.question('What is your favorite food?', function(answer) { console.log('Oh, so your favorite food is ' + answer); }); ``` -------------------------------- ### Log __filename example Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the resolved absolute path of the current file when running node example.js from /Users/mjr. ```javascript console.log(__filename); // /Users/mjr/example.js ``` -------------------------------- ### Zlib: Compress file with piping Source: https://nodejs.org/docs/v0.6.14/api/all.html Example from the Zlib module documentation. It compresses a file by piping an fs.ReadStream into a gzip stream and then into an fs.WriteStream. ```javascript var gzip = zlib.createGzip(); var fs = require('fs'); var inp = fs.createReadStream('input.txt'); var out = fs.createWriteStream('input.txt.gz'); inp.pipe(gzip).pipe(out); ``` -------------------------------- ### server.listen(path, [listeningListener]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Starts listening for connections on a Unix socket path. The listeningListener is added as a listener for the 'listening' event. ```APIDOC ## server.listen(path, [listeningListener]) ### Description Starts listening for connections on a Unix socket path. The listeningListener is added as a listener for the 'listening' event. ### Method listen ### Endpoint server.listen(path, [listeningListener]) ### Parameters - **path** (string) - Required - The Unix socket path. - **listeningListener** (function) - Optional - Listener for 'listening' event. ### Returns No return value. ### Example ```js var net = require('net'); var server = net.createServer(); server.listen('/tmp/echo.sock'); ``` ``` -------------------------------- ### server.listen(port, [host], [listeningListener]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Starts listening for connections on the specified port and host. The listeningListener is added as a listener for the 'listening' event. ```APIDOC ## server.listen(port, [host], [listeningListener]) ### Description Starts listening for connections on the specified port and host. The listeningListener is added as a listener for the 'listening' event. ### Method listen ### Endpoint server.listen(port, [host], [listeningListener]) ### Parameters - **port** (number) - Required - The port to listen on. - **host** (string) - Optional - The host to bind to. - **listeningListener** (function) - Optional - Listener for 'listening' event. ### Returns No return value. ### Example ```js var net = require('net'); var server = net.createServer(); server.listen(8080, 'localhost'); ``` ``` -------------------------------- ### Run example.js with node Source: https://nodejs.org/docs/v0.6.14/api/all.html Command to execute the server file and the expected output showing the server is running. ```bash > node example.js Server running at http://127.0.0.1:8124/ ``` -------------------------------- ### buf.copy() example Source: https://nodejs.org/docs/v0.6.14/api/all.html Copies a region from one buffer to another. The example copies bytes 16-19 from buf1 into buf2 starting at byte 8, producing '!!!!!!!!qrst!!!!!!!!!!!!!'. ```javascript buf1 = new Buffer(26); buf2 = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a buf2[i] = 33; // ASCII ! } buf1.copy(buf2, 8, 16, 20); console.log(buf2.toString('ascii', 0, 25)); // !!!!!!!!qrst!!!!!!!!!!!!! ``` -------------------------------- ### Loading a module with require() Source: https://nodejs.org/docs/v0.6.14/api/all.html Example of loading the circle module from foo.js and using its exported area function. ```javascript var circle = require('./circle.js'); console.log( 'The area of a circle of radius 4 is ' + circle.area(4)); ``` -------------------------------- ### Hello World HTTP server example Source: https://nodejs.org/docs/v0.6.14/api/all.html A basic Node.js web server that responds with 'Hello World' on port 8124. Save as example.js and run with node. ```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/'); ``` -------------------------------- ### Starting the REPL from the command line Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the interactive REPL session when running `node` without arguments. Demonstrates array assignment and forEach with multi-line input. ```text mjr:~$ node Type '.help' for options. > a = [ 1, 2, 3]; [ 1, 2, 3 ] > a.forEach(function (v) { ... console.log(v); ... }); 1 2 3 ``` -------------------------------- ### querystring.parse example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example of deserializing a query string to an object. ```javascript querystring.parse('foo=bar&baz=qux&baz=quux&corge') // returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' } ``` -------------------------------- ### repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Starts a REPL (Read-Eval-Print Loop) server. It can be customized with a prompt, stream, eval function, and options for global context and undefined handling. ```APIDOC ## [POST] repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined]) ### Description Starts a REPL (Read-Eval-Print Loop) server. It can be customized with a prompt, stream, eval function, and options for global context and undefined handling. ### Method POST ### Endpoint repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined]) ### Parameters #### Query Parameters - **prompt** (string) - Optional - The prompt to display. Default: '> '. - **stream** (stream) - Optional - The stream to read from and write to. Default: process.stdin and process.stdout. - **eval** (function) - Optional - The function to evaluate expressions. Default: an async wrapper for eval(). - **useGlobal** (boolean) - Optional - If true, use the global object instead of a separate context. Default: false. - **ignoreUndefined** (boolean) - Optional - If true, do not print the result of undefined expressions. Default: false. ### Request Example ```javascript var repl = require('repl'); repl.start({ prompt: 'node> ', useGlobal: true }); ``` ### Response #### Success Response (200) - **replServer** (REPLServer) - The started REPL server instance. #### Response Example ```javascript REPLServer object with methods like start, etc. ``` ``` -------------------------------- ### Log process.installPrefix Source: https://nodejs.org/docs/v0.6.14/api/all.html Logs the compiled-in NODE_PREFIX value. ```javascript console.log('Prefix: ' + process.installPrefix); ``` -------------------------------- ### Tiny command line interface using readline Source: https://nodejs.org/docs/v0.6.14/api/all.html Complete example combining line and close events, setPrompt, and prompt to create a simple CLI with a custom prefix. ```javascript var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout), prefix = 'OHAI> '; 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.setPrompt(prefix, prefix.length); rl.prompt(); }).on('close', function() { console.log('Have a great day!'); process.exit(0); }); console.log(prefix + 'Good to see you. Try typing stuff.'); rl.setPrompt(prefix, prefix.length); rl.prompt(); ``` -------------------------------- ### buf.slice([start], [end]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Returns a new buffer that references the same memory as the original, but with the specified start and end offsets. ```APIDOC ## buf.slice([start], [end]) ### Description Returns a new buffer that references the same memory as the original, but with the specified start and end offsets. ### Method buf.slice ### Parameters - **start** (Number) - Optional - The start offset. Defaults to 0. - **end** (Number) - Optional - The end offset. Defaults to the buffer length. ### Response Returns a new Buffer instance. ``` -------------------------------- ### Example package.json for folder module Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows a minimal package.json that specifies a main module. If placed in ./some-library, require('./some-library') loads ./some-library/lib/some-library.js. ```json { "name" : "some-library", "main" : "./lib/some-library.js" } ``` -------------------------------- ### wscript build file for compiling addons Source: https://nodejs.org/docs/v0.6.14/api/all.html Create this wscript file and run `node-waf configure build` to compile the addon examples. The build target is 'addon' and the source file is 'addon.cc'. ```python srcdir = '.' blddir = 'build' VERSION = '0.0.1' def set_options(opt): opt.tool_options('compiler_cxx') def configure(conf): conf.check_tool('compiler_cxx') conf.check_tool('node_addon') def build(bld): obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') obj.target = 'addon' obj.source = ['addon.cc'] ``` -------------------------------- ### http.get(options, callback) Source: https://nodejs.org/docs/v0.6.14/api/all.html Makes an HTTP GET request. Similar to http.request but sets the method to GET and calls req.end() automatically. ```APIDOC ## http.get(options, callback) ### Description Makes an HTTP GET request. Similar to http.request but sets the method to GET and calls req.end() automatically. ### Parameters - **options** (object) - Required - An object containing request options. - **callback** (function) - Required - Callback function that receives the response object. ### Returns - **http.ClientRequest** - The client request object. ### Example ```js http.get({host: 'example.com', path: '/'}, function(res) { console.log('STATUS: ' + res.statusCode); }); ``` ``` -------------------------------- ### C++ Hello World addon (hello.cc) Source: https://nodejs.org/docs/v0.6.14/api/all.html The C++ source file for the addon, defining the Method function and the init function, and registering the module with NODE_MODULE. ```cpp #include #include using namespace v8; Handle Method(const Arguments& args) { HandleScope scope; return scope.Close(String::New("world")); } void init(Handle target) { target->Set(String::NewSymbol("hello"), FunctionTemplate::New(Method)->GetFunction()); } NODE_MODULE(hello, init) ``` -------------------------------- ### buf.toString([encoding], [start], [end]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Decodes and returns a string from buffer data encoded with the specified encoding, beginning at start and ending at end. ```APIDOC ## buf.toString([encoding], [start], [end]) ### Description Decodes and returns a string from buffer data encoded with `encoding` (defaults to `'utf8'`) beginning at `start` (defaults to `0`) and ending at `end` (defaults to `buffer.length`). ### Parameters - **encoding** (String) - Optional - Default: 'utf8'. - **start** (Number) - Optional - Default: 0. - **end** (Number) - Optional - Default: `buffer.length`. ### Example ```js buf = new Buffer('Hello World'); console.log(buf.toString('utf8', 0, 5)); // 'Hello' ``` ``` -------------------------------- ### http.get(options, callback) Source: https://nodejs.org/docs/v0.6.14/api/all.html Convenience method for making GET requests. It is equivalent to http.request with the method set to 'GET' and automatically calls req.end(). ```APIDOC ## [GET] http.get(options, callback) ### Description Convenience method for making GET requests. It is equivalent to http.request with the method set to 'GET' and automatically calls req.end(). ### Method GET ### Endpoint http.get(options, callback) ### Parameters #### Options Object - **host** (string) - Optional - Domain name or IP address of the server to issue the request to. - **port** (number) - Optional - Port of remote server. - **method** (string) - Optional - HTTP request method. Default: 'GET'. - **path** (string) - Optional - Request path. Default: '/'. - **headers** (object) - Optional - HTTP headers object. - **auth** (string) - Optional - Basic authentication i.e. 'user:password' to compute an Authorization header. - **agent** (Agent) - Optional - Controls Agent behavior. Default: http.globalAgent. #### Callback - **callback** (function) - Required - The callback is invoked with a single argument that is the instance of http.ClientResponse. ### Request Example ```javascript http.get({ host: 'www.google.com', path: '/' }, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); ``` ### Response #### Success Response (200) - **statusCode** (number) - HTTP status code of the response. - **httpVersion** (string) - HTTP protocol version. - **headers** (object) - HTTP response headers. - **trailers** (object) - HTTP response trailers. #### Response Example ```javascript { statusCode: 200, httpVersion: '1.1', headers: { 'content-type': 'text/html', ... }, trailers: {} } ``` ``` -------------------------------- ### path.resolve example with cd sequence Source: https://nodejs.org/docs/v0.6.14/api/all.html Resolves a path to an absolute path. The example shows a path.resolve call and its equivalent sequence of cd commands in a shell. ```javascript path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile') ``` ```shell cd foo/bar cd /tmp/file/ cd .. cd a/../subfile pwd ``` -------------------------------- ### process.installPrefix Source: https://nodejs.org/docs/v0.6.14/api/all.html A compiled-in property that exposes NODE_PREFIX. ```APIDOC ## process.installPrefix ### Description A compiled-in property that exposes NODE_PREFIX. ### Method N/A (property) ### Endpoint N/A ### Parameters None ### Request Example ``` console.log('Prefix: ' + process.installPrefix); ``` ### Response #### Success Response (200) - **value** (string) - The installation prefix (NODE_PREFIX) #### Response Example ``` Prefix: /usr/local ``` ``` -------------------------------- ### https.get(options, callback) Source: https://nodejs.org/docs/v0.6.14/api/all.html Convenience method for making GET requests over HTTPS. It is equivalent to https.request with the method set to 'GET' and automatically calls req.end(). ```APIDOC ## [GET] https.get(options, callback) ### Description Convenience method for making GET requests over HTTPS. It is equivalent to https.request with the method set to 'GET' and automatically calls req.end(). ### Method GET ### Endpoint https.get(options, callback) ### Parameters #### Options Object - **host** (string) - Optional - Domain name or IP address of the server to issue the request to. - **port** (number) - Optional - Port of remote server. - **method** (string) - Optional - HTTP request method. Default: 'GET'. - **path** (string) - Optional - Request path. Default: '/'. - **headers** (object) - Optional - HTTP headers object. - **auth** (string) - Optional - Basic authentication i.e. 'user:password' to compute an Authorization header. - **agent** (Agent) - Optional - Controls Agent behavior. Default: https.globalAgent. - **key** (string) - Optional - Private key for SSL/TLS. - **cert** (string) - Optional - Public x509 certificate for SSL/TLS. - **ca** (array) - Optional - An array of strings or Buffer of trusted certificates. #### Callback - **callback** (function) - Required - The callback is invoked with a single argument that is the instance of http.ClientResponse. ### Request Example ```javascript https.get({ host: 'encrypted.google.com', path: '/' }, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); }); }); ``` ### Response #### Success Response (200) - **statusCode** (number) - HTTP status code of the response. - **httpVersion** (string) - HTTP protocol version. - **headers** (object) - HTTP response headers. - **trailers** (object) - HTTP response trailers. #### Response Example ```javascript { statusCode: 200, httpVersion: '1.1', headers: { 'content-type': 'text/html', ... }, trailers: {} } ``` ``` -------------------------------- ### fs.watch example with filename fallback Source: https://nodejs.org/docs/v0.6.14/api/all.html Example of using fs.watch to watch a directory. The callback receives (event, filename) and checks if filename is provided, as it is not guaranteed on all platforms. ```javascript fs.watch('somedir', function (event, filename) { console.log('event is: ' + event); if (filename) { console.log('filename provided: ' + filename); } else { console.log('filename not provided'); } }); ``` -------------------------------- ### repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Starts a REPL with the given prompt and stream. The prompt defaults to '>', and the stream defaults to process.stdin. The eval function defaults to an async wrapper for eval(). If useGlobal is true, the REPL uses the global object instead of a separate context. If ignoreUndefined is true, the REPL will not output the return value if it is undefined. ```APIDOC ## repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined]) ### Description Starts a REPL with the given prompt and stream. The prompt defaults to '>', and the stream defaults to process.stdin. The eval function defaults to an async wrapper for eval(). If useGlobal is true, the REPL uses the global object instead of a separate context. If ignoreUndefined is true, the REPL will not output the return value if it is undefined. ### Method start ### Parameters #### Optional Parameters - **prompt** (string) - Optional - The prompt to display. Defaults to '>'. - **stream** (stream) - Optional - The stream for all I/O. Defaults to process.stdin. - **eval** (function) - Optional - A custom eval function with signature `function eval(cmd, callback) { callback(null, result); }`. Defaults to an async wrapper for eval(). - **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 if it is undefined. Defaults to false. ### Example ```javascript var net = require("net"), repl = require("repl"); connections = 0; repl.start("node via stdin> "); net.createServer(function (socket) { connections += 1; repl.start("node via Unix socket> ", socket); }).listen("/tmp/node-repl-sock"); net.createServer(function (socket) { connections += 1; repl.start("node via TCP socket> ", socket); }).listen(5001); ``` ``` -------------------------------- ### Require the custom module and listen for 'ready' event Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows how to require the module defined in a.js and listen for the 'ready' event. This example is used in the documentation to demonstrate using the custom module.exports object. ```javascript var a = require('./a'); a.on('ready', function() { console.log('module a is ready'); }); ``` -------------------------------- ### os.uptime() Source: https://nodejs.org/docs/v0.6.14/api/all.html Returns the system uptime in seconds. ```APIDOC ## os.uptime() ### Description Returns the system uptime in seconds. ### Method uptime ### Returns - **number** - The uptime in seconds. ``` -------------------------------- ### WAF build script (wscript) Source: https://nodejs.org/docs/v0.6.14/api/all.html Python build script for WAF to compile the addon into hello.node. ```python srcdir = '.' blddir = 'build' VERSION = '0.0.1' def set_options(opt): opt.tool_options('compiler_cxx') def configure(conf): conf.check_tool('compiler_cxx') conf.check_tool('node_addon') def build(bld): obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') obj.target = 'hello' obj.source = 'hello.cc' ``` -------------------------------- ### a.js - Circular require example Source: https://nodejs.org/docs/v0.6.14/api/all.html First module in the circular dependency example. It 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'); ``` -------------------------------- ### main.js - Entry point for circular require example Source: https://nodejs.org/docs/v0.6.14/api/all.html Entry point that loads a.js and b.js, demonstrating the final state of both modules after the circular dependency resolves. ```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); ``` -------------------------------- ### Default options for fs.createReadStream Source: https://nodejs.org/docs/v0.6.14/api/all.html Lists the default options object for fs.createReadStream. The options can include start and end values to read a byte range; both are inclusive and start at 0. ```text { flags: 'r', encoding: null, fd: null, mode: 0666, bufferSize: 64 * 1024 } ``` -------------------------------- ### Listening for 'upgrade' event with http.getAgent Source: https://nodejs.org/docs/v0.6.14/api/all.html Complete client-server example showing how to listen for the 'upgrade' event using http.getAgent. The server responds to upgrade requests with a WebSocket handshake and echoes data; the client sends a request with Upgrade headers and logs 'got upgraded!'. ```javascript var http = require('http'); var net = require('net'); // Create an HTTP server var srv = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('okay'); }); srv.on('upgrade', function(req, socket, upgradeHead) { socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n\r\n'); socket.ondata = function(data, start, end) { socket.write(data.toString('utf8', start, end), 'utf8'); // echo back }; }); // now that server is running srv.listen(1337, '127.0.0.1', function() { // make a request var options = { port: 1337, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket' } }; var req = http.request(options); req.end(); req.on('upgrade', function(res, socket, upgradeHead) { console.log('got upgraded!'); socket.end(); process.exit(0); }); }); ``` -------------------------------- ### https.get() example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example of using https.get() to make an HTTPS request, similar to http.get(). It logs the status code and headers, streams the response data to stdout, and handles errors. ```javascript var https = require('https'); https.get({ host: 'encrypted.google.com', path: '/' }, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); }); }).on('error', function(e) { console.error(e); }); ``` -------------------------------- ### b.js - Circular require example Source: https://nodejs.org/docs/v0.6.14/api/all.html Second module in the circular dependency example. It requires a.js while a.js is still loading, receiving an unfinished copy of a.js's exports. ```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'); ``` -------------------------------- ### Start debugger with node debug myscript.js Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the output when starting the debugger with `node debug myscript.js`. The debugger listens on port 5858 and breaks at the first line of the script. ```text % node 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> ``` -------------------------------- ### Create HTTPS server with https.createServer Source: https://nodejs.org/docs/v0.6.14/api/all.html Creates an HTTPS server that responds with 'hello world'. Requires a private key and certificate file. Test with 'curl -k https://localhost:8000/'. ```javascript // curl -k https://localhost:8000/ var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); ``` -------------------------------- ### Using the addon in Node.js (hello.js) Source: https://nodejs.org/docs/v0.6.14/api/all.html JavaScript code to load the built addon and call the hello function. ```javascript var addon = require('./build/Release/hello'); console.log(addon.hello()); // 'world' ``` -------------------------------- ### Synchronous fs.unlinkSync example Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the synchronous form of fs.unlinkSync, which throws exceptions immediately. The example deletes '/tmp/hello' and logs a success message. Synchronous versions block the entire process until completion. ```javascript var fs = require('fs'); fs.unlinkSync('/tmp/hello') console.log('successfully deleted /tmp/hello'); ``` -------------------------------- ### buf.slice([start], [end]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Returns a new buffer that references the same memory as the original, offset and cropped by the start and end indexes. 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. Modifying the new buffer slice will modify memory in the original buffer. ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. ### Request 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 ``` ### Response #### Success Response (200) - **Buffer** - A new buffer referencing the same memory as the original, offset and cropped by the start and end indexes. #### Response Example ```javascript // abc // !bc ``` ``` -------------------------------- ### vm.createContext([initSandbox]) Source: https://nodejs.org/docs/v0.6.14/api/all.html Creates a new V8 context that can be used with vm.runInContext. The optional initSandbox object is used as the global object for the new context. ```APIDOC ## vm.createContext([initSandbox]) ### Description Creates a new V8 context that can be used with vm.runInContext. The optional initSandbox object is used as the global object for the new context. ### Method createContext ### Parameters - **initSandbox** (object) - Optional - An object that will be used as the global object for the new context. ### Returns - A contextified object that can be passed to vm.runInContext. ### Example ```javascript var vm = require('vm'); var context = vm.createContext({}); ``` ``` -------------------------------- ### Echo server example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example of an echo server listening on port 8124. The connection listener logs connection and disconnection, writes 'hello\r\n', and pipes the socket to itself. The listening listener logs 'server bound'. ```javascript var net = require('net'); var server = net.createServer(function(c) { //'connection' listener console.log('server connected'); c.on('end', function() { console.log('server disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.listen(8124, function() { //'listening' listener console.log('server bound'); }); ``` -------------------------------- ### http.request POST example Source: https://nodejs.org/docs/v0.6.14/api/all.html Example of using http.request to make a POST request. The ClientRequest instance is a writable stream; write data to it and always call req.end() to signify completion. An 'error' event is emitted on request errors. ```javascript var options = { host: 'www.google.com', port: 80, path: '/upload', method: 'POST' }; var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write('data\n'); req.write('data\n'); req.end(); ``` -------------------------------- ### myobject.cc: Implementation of MyObject Source: https://nodejs.org/docs/v0.6.14/api/all.html Implements MyObject methods: constructor, destructor, Init, New, and NewInstance. New sets val_ from the first argument (default 0) and wraps the instance. ```cpp #define BUILDING_NODE_EXTENSION #include #include "myobject.h" using namespace v8; MyObject::MyObject() {}; MyObject::~MyObject() {}; Persistent MyObject::constructor; void MyObject::Init() { // Prepare constructor template Local tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("MyObject")); tpl->InstanceTemplate()->SetInternalFieldCount(1); constructor = Persistent::New(tpl->GetFunction()); } Handle MyObject::New(const Arguments& args) { HandleScope scope; MyObject* obj = new MyObject(); obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(); obj->Wrap(args.This()); return args.This(); } Handle MyObject::NewInstance(const Arguments& args) { HandleScope scope; const unsigned argc = 1; Handle argv[argc] = { args[0] }; Local instance = constructor->NewInstance(argc, argv); return scope.Close(instance); } ``` -------------------------------- ### Log platform with process.platform Source: https://nodejs.org/docs/v0.6.14/api/all.html Prints the platform (e.g., 'linux2', 'darwin') to the console. ```javascript console.log('This platform is ' + process.platform); ``` -------------------------------- ### Asynchronous fs.unlink example Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows the asynchronous form of fs.unlink, which takes a completion callback as its last argument. The first callback argument is reserved for an exception; on success it is null or undefined. The example deletes '/tmp/hello' and logs a success message. ```javascript var fs = require('fs'); fs.unlink('/tmp/hello', function (err) { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); ``` -------------------------------- ### process.execPath Source: https://nodejs.org/docs/v0.6.14/api/all.html The absolute pathname of the executable that started the process. ```APIDOC ## process.execPath ### Description This is the absolute pathname of the executable that started the process. ### Example ``` /usr/local/bin/node ``` ``` -------------------------------- ### Run code in a sandbox with vm.runInNewContext Source: https://nodejs.org/docs/v0.6.14/api/all.html Shows how to compile and execute code in a sandbox object. The sandbox is used as the global object, and the example increments a global variable and adds a new one. The output shows the sandbox now has count: 3 and name: 'kitty'. ```javascript var util = require('util'), vm = require('vm'), sandbox = { animal: 'cat', count: 2 }; vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm'); console.log(util.inspect(sandbox)); // { animal: 'cat', count: 3, name: 'kitty' } ``` -------------------------------- ### fs.statSync(path) Source: https://nodejs.org/docs/v0.6.14/api/all.html Synchronously gets file status. ```APIDOC ## fs.statSync(path) ### Description Synchronously gets file status. ### Method statSync ### Parameters - **path** (string) - Required - Path to the file. ``` -------------------------------- ### response.removeHeader example Source: https://nodejs.org/docs/v0.6.14/api/all.html Removes a header that is queued for implicit sending. ```javascript response.removeHeader("Content-Encoding"); ``` -------------------------------- ### Event: 'listening' Source: https://nodejs.org/docs/v0.6.14/api/all.html Emitted when the socket starts listening for datagrams. ```APIDOC ## Event: 'listening' ### Description Emitted when the socket starts listening for datagrams. ### Event listening ### Endpoint socket.on('listening', callback) ### Parameters None ### Response No data passed to the callback. ``` -------------------------------- ### response.getHeader(name) Source: https://nodejs.org/docs/v0.6.14/api/all.html Gets the value of a header that has been set on the response. ```APIDOC ## response.getHeader(name) ### Description Gets the value of a header that has been set on the response. ### Parameters - **name** (string) - Required - The header name. ### Returns - **string** - The header value, or undefined if not set. ### Example ```js var contentType = response.getHeader('Content-Type'); ``` ``` -------------------------------- ### rl.question(query, callback) Source: https://nodejs.org/docs/v0.6.14/api/all.html Prepends the prompt with the specified query and invokes the callback with the user's response. ```APIDOC ## [POST] rl.question(query, callback) ### Description Prepends the prompt with the specified query and invokes the callback with the user's response. ### Method POST ### Endpoint rl.question(query, callback) ### Parameters #### Path Parameters - **query** (string) - Required - The question to display. - **callback** (function) - Required - The callback to invoke with the user's answer. ### Request Example ```javascript rl.question('What is your name? ', function(answer) { console.log('Hello, ' + answer); rl.close(); }); ``` ### Response #### Success Response (200) - **answer** (string) - The user's response. #### Response Example ```javascript 'John' ``` ```