Github Node
Github Node
/* *******************************************************************************************
* SYNOPSIS
* http://nodejs.org/api/synopsis.html
* ******************************************************************************************* */
// An example of a web server written with Node which responds with 'Hello World'.
// To run the server, put the code into a file called example.js and execute it with the node
program.
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://nodejs.org/api/globals.html
* ******************************************************************************************* */
/* *******************************************************************************************
* CONSOLE
* http://nodejs.org/api/console.html
* ******************************************************************************************* */
/* *******************************************************************************************
* TIMERS
* http://nodejs.org/api/timers.html
* ******************************************************************************************* */
unref(); // Allow you to create a timer that is active but if it is the only item left in the
event loop, node won't keep the program running.
ref(); // If you had previously unref()d a timer you can call ref() to explicitly request the
timer hold the program open.
/* *******************************************************************************************
* MODULES
* http://nodejs.org/api/modules.html
* ******************************************************************************************* */
var module = require('./module.js'); // Loads the module module.js in the same directory.
module.require('./another_module.js'); // load another_module as if require() was called from the
module itself.
module.id; // The identifier for the module. Typically this is the fully resolved filename.
module.filename; // The fully resolved filename to the module.
module.loaded; // Whether or not the module is done loading, or is in the process of loading.
module.parent; // The module that required this one.
module.children; // The module objects required by this one.
// If you want the root of your module's export to be a function (such as a constructor)
// or if you want to export a complete object in one assignment instead of building it one
property at a time,
// assign it to module.exports instead of exports.
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
/* *******************************************************************************************
* PROCESS
* http://nodejs.org/api/process.html
* ******************************************************************************************* */
process.abort(); // This causes node to emit an abort. This will cause node to exit and
generate a core file.
process.chdir(dir); // Changes the current working directory of the process or throws an
exception if that fails.
process.cwd(); // Returns the current working directory of the process.
process.exit([code]); // Ends the process with the specified code. If omitted, exit uses the
'success' code 0.
process.getgid(); // Gets the group identity of the process.
process.setgid(id); // Sets the group identity of the process.
process.getuid(); // Gets the user identity of the process.
process.setuid(id); // Sets the user identity of the process.
process.getgroups(); // Returns an array with the supplementary group IDs.
process.setgroups(grps); // Sets the supplementary group IDs.
process.initgroups(user, extra_grp); // Reads /etc/group and initializes the group access list,
using all groups of which the user is a member.
process.kill(pid, [signal]); // Send a signal to a process. pid is the process id and
signal is the string describing the signal to send.
process.memoryUsage(); // Returns an object describing the memory usage of the Node
process measured in bytes.
process.nextTick(callback); // On the next loop around the event loop call this
callback.
process.maxTickDepth; // Callbacks passed to process.nextTick will usually be
called at the end of the current flow of execution, and are thus approximately as fast as calling
a function synchronously.
process.umask([mask]); // Sets or reads the process's file mode creation mask.
process.uptime(); // Number of seconds Node has been running.
process.hrtime(); // Returns the current high-resolution real time in a
[seconds, nanoseconds] tuple Array.
/* *******************************************************************************************
* CHILD PROCESS
* http://nodejs.org/api/child_process.html
* ******************************************************************************************* */
/* *******************************************************************************************
* UTIL
* http://nodejs.org/api/util.html
* ******************************************************************************************* */
// These functions are in the module 'util'. Use require('util') to access them.
util.format(format, [...]); // Returns a formatted string using the first argument as a printf-
like format. (%s, %d, %j)
util.debug(string); // A synchronous output function. Will block the process and output
string immediately to stderr.
util.error([...]); // Same as util.debug() except this will output all arguments
immediately to stderr.
util.puts([...]); // A synchronous output function. Will block the process and output
all arguments to stdout with newlines after each argument.
util.print([...]); // A synchronous output function. Will block the process, cast each
argument to a string then output to stdout. (no newlines)
util.log(string); // Output with timestamp on stdout.
util.inspect(object, [opts]); // Return a string representation of object, which is useful for
debugging. (options: showHidden, depth, colors, customInspect)
util.isArray(object); // Returns true if the given "object" is an Array. false otherwise.
util.isRegExp(object); // Returns true if the given "object" is a RegExp. false otherwise.
util.isDate(object); // Returns true if the given "object" is a Date. false otherwise.
/* *******************************************************************************************
* EVENTS
* http://nodejs.org/api/events.html
* ******************************************************************************************* */
// All objects which emit events are instances of events.EventEmitter. You can access this module
by doing: require("events");
// To access the EventEmitter class, require('events').EventEmitter.
// All EventEmitters emit the event 'newListener' when new listeners are added and
'removeListener' when a listener is removed.
/* *******************************************************************************************
* STREAM
* http://nodejs.org/api/stream.html
* ******************************************************************************************* */
// A stream is an abstract interface implemented by various objects in Node. For example a request
to an HTTP server is a stream, as is stdout.
// Streams are readable, writable, or both. All streams are instances of EventEmitter.
// The Readable stream interface is the abstraction for a source of data that you are reading
from.
// In other words, data comes out of a Readable stream.
// A Readable stream will not start emitting data until you indicate that you are ready to receive
it.
// Examples of readable streams include: http responses on the client, http requests on the
server, fs read streams
// zlib streams, crypto streams, tcp sockets, child process stdout and stderr, process.stdin.
readable.on('readable', function() {}); // When a chunk of data can be read from the stream, it
will emit a 'readable' event.
readable.on('data', function(chunk) {}); // If you attach a data event listener, then it will
switch the stream into flowing mode, and data will be passed to your handler as soon as it is
available.
readable.on('end', function() {}); // This event fires when there will be no more data to
read.
readable.on('close', function() {}); // Emitted when the underlying resource (for example,
the backing file descriptor) has been closed. Not all streams will emit this.
readable.on('error', function() {}); // Emitted if there was an error receiving data.
// The read() method pulls some data out of the internal buffer and returns it. If there is no
data available, then it will return null.
// This method should only be called in non-flowing mode. In flowing-mode, this method is called
automatically until the internal buffer is drained.
readable.read([size]);
// The Writable stream interface is an abstraction for a destination that you are writing data to.
// Examples of writable streams include: http requests on the client, http responses on the
server, fs write streams,
// zlib streams, crypto streams, tcp sockets, child process stdin, process.stdout, process.stderr.
writable.write(chunk, [encoding], [callback]); // This method writes some data to the underlying
system, and calls the supplied callback once the data has been fully handled.
writer.once('drain', write); // If a writable.write(chunk) call returns false,
then the drain event will indicate when it is appropriate to begin writing more data to the
stream.
writable.end([chunk], [encoding], [callback]); // Call this method when no more data will be
written to the stream.
writer.on('finish', function() {}); // When the end() method has been called, and all
data has been flushed to the underlying system, this event is emitted.
writer.on('pipe', function(src) {}); // This is emitted whenever the pipe() method is
called on a readable stream, adding this writable to its set of destinations.
writer.on('unpipe', function(src) {}); // This is emitted whenever the unpipe() method is
called on a readable stream, removing this writable from its set of destinations.
writer.on('error', function(src) {}); // Emitted if there was an error when writing or
piping data.
// Duplex streams are streams that implement both the Readable and Writable interfaces. See above
for usage.
// Examples of Duplex streams include: tcp sockets, zlib streams, crypto streams.
// Transform streams are Duplex streams where the output is in some way computed from the input.
They implement both the Readable and Writable interfaces. See above for usage.
/* *******************************************************************************************
* FILE SYSTEM
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
fs.chown(path, uid, gid, callback); // Asynchronous chown. No arguments other than a possible
exception are given to the completion callback.
fs.chownSync(path, uid, gid); // Synchronous chown.
fs.fchown(fd, uid, gid, callback); // Asynchronous fchown. No arguments other than a possible
exception are given to the completion callback.
fs.fchownSync(fd, uid, gid); // Synchronous fchown.
fs.lchown(path, uid, gid, callback); // Asynchronous lchown. No arguments other than a possible
exception are given to the completion callback.
fs.lchownSync(path, uid, gid); // Synchronous lchown.
platforms)
fs.symlinkSync(srcpath, dstpath, [type]); // Synchronous symlink.
fs.readlink(path, callback); // Asynchronous readlink. The callback gets two
arguments (err, linkString).
fs.readlinkSync(path); // Synchronous readlink. Returns the symbolic
link's string value.
fs.unlink(path, callback); // Asynchronous unlink. No arguments other than a
possible exception are given to the completion callback.
fs.unlinkSync(path); // Synchronous unlink.
fs.write(fd, buffer, offset, length, position, callback); // Write buffer to the file specified
by fd.
fs.writeSync(fd, buffer, offset, length, position); // Synchronous version of fs.write().
Returns the number of bytes written.
fs.read(fd, buffer, offset, length, position, callback); // Read data from the file specified by
fd.
fs.readSync(fd, buffer, offset, length, position); // Synchronous version of fs.read.
Returns the number of bytesRead.
fs.readFile(filename, [options], callback); // Asynchronously reads the entire
contents of a file.
fs.readFileSync(filename, [options]); // Synchronous version of fs.readFile.
Returns the contents of the filename. If the encoding option is specified then this function
returns a string. Otherwise it returns a buffer.
callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename
is the name of the file which triggered the event.
fs.exists(path, callback); // Test whether or not the given path exists
by checking with the file system. Then call the callback argument with either true or false.
(should not be used)
fs.existsSync(path); // Synchronous version of fs.exists. (should
not be used)
// fs.Stats: objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous
counterparts are of this type.
stats.isFile();
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() // (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
/* *******************************************************************************************
* PATH
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
/* *******************************************************************************************
* HTTP
* http://nodejs.org/api/http.html
* ******************************************************************************************* */
response body. If this method is called and response.writeHead() has not been called, it will
switch to implicit header mode and flush the implicit headers.
response.writeContinue(); // Sends a HTTP/1.1 100 Continue
message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the
request.
response.setTimeout(msecs, callback); // Sets the Socket's timeout value
to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the
response object.
response.setHeader(name, value); // Sets a single header value for
implicit headers. If this header already exists in the to-be-sent headers, its value will be
replaced. Use an array of strings here if you need to send multiple headers with the same name.
response.getHeader(name); // Reads out a header that's
already been queued but not sent to the client. Note that the name is case insensitive.
response.removeHeader(name); // Removes a header that's queued
for implicit sending.
response.addTrailers(headers); // This method adds HTTP trailing
headers (a header but at the end of the message) to the response.
response.end([data], [encoding]); // This method signals to the
server that all of the response headers and body have been sent; that server should consider this
message complete. The method, response.end(), MUST be called on each response.
response.on('close', function () { }); // Indicates that the underlying connection was terminated
before response.end() was called or able to flush.
response.on('finish', function() { }); // Emitted when the response has been sent.
/* *******************************************************************************************
* URL
* http://nodejs.org/api/url.html
* ******************************************************************************************* */
// This module has utilities for URL resolution and parsing. Call require('url') to use it.
/* *******************************************************************************************
* QUERY STRING
* http://nodejs.org/api/querystring.html
* ******************************************************************************************* */
// This module provides utilities for dealing with query strings. Call require('querystring') to
use it.
/* *******************************************************************************************
* ASSERT
* http://nodejs.org/api/assert.html
* ******************************************************************************************* */
// This module is used for writing unit tests for your applications, you can access it with
require('assert').
/* *******************************************************************************************
* OS
* http://nodejs.org/api/os.html
* ******************************************************************************************* */
os.tmpdir(); // Returns the operating system's default directory for temp files.
os.endianness(); // Returns the endianness of the CPU. Possible values are "BE" or "LE".
os.hostname(); // Returns the hostname of the operating system.
/* *******************************************************************************************
* BUFFER
* http://nodejs.org/api/buffer.html
* ******************************************************************************************* */