/* *******************************************************************************************
* THE UPDATED VERSION IS AVAILABLE AT
* https://github.com/LeCoupa/awesome-cheatsheets
* ******************************************************************************************* */
// 0. Synopsis.
// http://nodejs.org/api/synopsis.html
var http = require('http');
// 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);
console.log('Server running at http://127.0.0.1:8124/');
// 1. Global Objects.
// http://nodejs.org/api/globals.html
// In browsers, the top-level scope is the global scope.
// That means that in browsers if you're in the global scope var something will define a global variable.
// In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
__filename; // The filename of the code being executed. (absolute path)
__dirname; // The name of the directory that the currently executing script resides in. (absolute path)
module; // A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().
exports; // A reference to the module.exports that is shorter to type.
process; // The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.
Buffer; // The Buffer class is a global type for dealing with binary data directly.
// 2. Console.
// http://nodejs.org/api/console.html
console.log([data], [...]); // Prints to stdout with newline.
console.info([data], [...]); // Same as console.log.
console.error([data], [...]); // Same as console.log but prints to stderr.
console.warn([data], [...]); // Same as console.error.
console.dir(obj); // Uses util.inspect on obj and prints resulting string to stdout.
console.time(label); // Mark a time.
console.timeEnd(label); // Finish timer, record output.
console.trace(label); // Print a stack trace to stderr of the current position.
console.assert(expression, [message]); // Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.
// 3. Timers.
// http://nodejs.org/api/timers.html
setTimeout(callback, delay, [arg], [...]); // To schedule execution of a one-time callback after delay milliseconds. Optionally you can also pass arguments to the callback.
clearTimeout(t); // Stop a timer that was previously created with setTimeout().
setInterval(callback, delay, [arg], [...]); // To schedule the repeated execution of callback every delay milliseconds. Optionally you can also pass arguments to the callback.
clearInterval(t); // Stop a timer that was previously created with setInterval().
setImmediate(callback, [arg], [...]); // To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval.
clearImmediate(immediateObject); // Stop a timer that was previously created with setImmediate().
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.
// 4. 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.
exports.area = function (r) {
return 3.14 * r * r;
};
// 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;
}
};
}
// 5. Process.
// http://nodejs.org/api/process.html
process.on('exit', function(code) {}); // Emitted when the process is about to exit
process.on('uncaughtException', function(err) {}); // Emitted when an exception bubbles all the way back to the event loop. (should not be used)
process.stdout; // A writable stream to stdout.
process.stderr; // A writable stream to stderr.
process.stdin; // A readable stream for stdin.
process.argv; // An array containing the command line arguments.
process.env; // An object containing the user environment.
process.execPath; // This is the absolute pathname of the executable that started the process.
process.execArgv; // This is the set of node-specific command line options from the executable that started the process.
process.arch; // What processor architecture you're running on: 'arm', 'ia32', or 'x64'.
process.config; // An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.
process.pid; // The PID of the process.
process.platform; // What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'.
process.title; // Getter/setter to set what is displayed in 'ps'.
process.version; // A compiled-in property that exposes NODE_VERSION.
process.versions; // A property exposing version strings of node and its dependencies.
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.
// 6. Child Process.
// Node provides a tri-directional popen facility through the child_process module.
// It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way.
// http://nodejs.org/api/child_process.html
ChildProcess; // Class. ChildProcess is an EventEmitter.
child.stdin; // A Writable Stream that represents the child process's stdin
child.stdout; // A Readable Stream that represents the child process's stdout
child.stderr; // A Readable Stream that represents the child process's stderr.
child.pid; // The PID of the child process
child.connected; // If .connected is false, it is no longer possible to send messages
child.kill([signal]); // Send a signal to the child process
child.send(message, [sendHandle]); // When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.
child.disconnect(); // Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive.
child_process.spawn(command, [args], [options]); // Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
child_process.exec(command, [options], callback); // Runs a command in a shell and buffers the output.
child_process.execFile(file, [args], [options], [callback]); // Runs a command in a shell and buffers the output.
child_process.fork(modulePath, [args], [options]); // This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in.
// 7. Util.
// These functions are in the module 'util'. Use require('util') to access them.
// http://nodejs.org/api/util.html
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.
util.isError(object); // Returns true if the given "object" is an Error. false otherwise.
util.inherits(constructor, superConstructor); // Inherit the prototype methods from one constructor into another.
// 8. Events.
// 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.
// http://nodejs.org/api/events.html
emitter.addListener(event, listener); // Adds a listener to the end of the listeners array for the specified event.
emitter.on(event, listener); // Same as emitter.addListener().
emitter.once(event, listener); // Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
emitter.removeListener(event, listener); // Remove a listener from the listener array for the specified event.
emitter.removeAllListeners([event]); // Removes all listeners, or those of the specified event.
emitter.setMaxListeners(n); // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.
emitter.listeners(event); // Returns an array of listeners for the specified event.
emitter.emit(event, [arg1], [arg2], [...]); // Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.
EventEmitter.listenerCount(emitter, event); // Return the number of listeners for a given event.
// 9. Stream.
// 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.
// http://nodejs.org/api/stream.html
// 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.
var readable = getReadableStreamSomehow();
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]);
readable.setEncoding(encoding); // Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
readable.resume(); // This method will cause the readable stream to resume emitting data events.
readable.pause(); // This method will cause a stream in flowing-mode to stop emitting data events.
readable.pipe(destination, [options]); // This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
readable.unpipe([destination]); // This method will remove the hooks set up for a previous pipe() call. If the destination is not specified, then all pipes are removed.
readable.unshift(chunk); // This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
// 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.
var writer = getWritableStreamSomehow();
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.
// Examples of Transform streams include: zlib streams, crypto streams.
// 10. File System.
// To use this module do require('fs').
// All the methods have asynchronous and synchronous forms.
// http://nodejs.org/api/fs.html
fs.rename(oldPath, newPath, callback); // Asynchronous rename. No arguments other than a possible exception are given to the completion callback.Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.renameSync(oldPath, newPath); // Synchronous rename.
fs.ftruncate(fd, len, callback); // Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.ftruncateSync(fd, len); // Synchronous ftruncate.
fs.truncate(path, len, callback); // Asynchronous truncate. No arguments other than a possible exception are given to the completion callback.
fs.truncateSync(path, len); // Synchronous truncate.
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.
fs.chmod(path, mode, callback); // Asynchronous chmod. No arguments other than a possible exception are given to the completion callback.
fs.chmodSync(path, mode); // Synchronous chmod.
fs.fchmod(fd, mode, callback); // Asynchronous fchmod. No arguments other than a possible exception are given to the completion callback.
fs.fchmodSync(fd, mode); // Synchronous fchmod.
fs.lchmod(path, mode, callback); // Asynchronous lchmod. No arguments other than a possible exception are given to the completion callback.
fs.lchmodSync(path, mode); // Synchronous lchmod.
fs.stat(path, callback); // Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.
fs.statSync(path); // Synchronous stat. Returns an instance of fs.Stats.
fs.lstat(path, callback); // Asynchronous lstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fs.lstatSync(path); // Synchronous lstat. Returns an instance of fs.Stats.
fs.fstat(fd, callback); // Asynchronous fstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
fs.fstatSync(fd); // Synchronous fstat. Returns an instance of fs.Stats.
fs.link(srcpath, dstpath, callback); // Asynchronous link. No arguments other than a possible exception are given to the completion callback.
fs.linkSync(srcpath, dstpath); // Synchronous link.
fs.symlink(srcpath, dstpath, [type], callback); // Asynchronous symlink. No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other 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.realpath(path, [cache], callback); // Asynchronous realpath. The callback gets two arguments (err, resolvedPath).
fs.realpathSync(path, [cache]); // Synchronous realpath. Returns the resolved path.
fs.rmdir(path, callback); // Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.
fs.rmdirSync(path); // Synchronous rmdir.
fs.mkdir(path, [mode], callback); // Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.
fs.mkdirSync(path, [mode]); // Synchronous mkdir.
fs.readdir(path, callback); // Asynchronous readdir. Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path); // Synchronous readdir. Returns an array of filenames excluding '.' and '..'.
fs.close(fd, callback); // Asynchronous close. No arguments other than a possible exception are given to the completion callback.
fs.closeSync(fd); // Synchronous close.
fs.open(path, flags, [mode], callback); // Asynchronous file open.
fs.openSync(path, flags, [mode]); // Synchronous version of fs.open().
fs.utimes(path, atime, mtime, callback); // Change file timestamps of the file referenced by the supplied path.
fs.utimesSync(path, atime, mtime); // Synchronous version of fs.utimes().
fs.futimes(fd, atime, mtime, callback); // Change the file timestamps of a file referenced by the supplied file descriptor.
fs.futimesSync(fd, atime, mtime); // Synchronous version of fs.futimes().
fs.fsync(fd, callback); // Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.
fs.fsyncSync(fd); // Synchronous fsync.
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.
fs.writeFile(filename, data, [options], callback); // Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
fs.writeFileSync(filename, data, [options]); // The synchronous version of fs.writeFile.
fs.appendFile(filename, data, [options], callback); // Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.
fs.appendFileSync(filename, data, [options]); // The synchronous version of fs.appendFile.
fs.watch(filename, [options], [listener]); // Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher. The listener 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()
fs.createReadStream(path, [options]); // Returns a new ReadStream object.
fs.createWriteStream(path, [options]); // Returns a new WriteStream object.
// 11. Path.
// Use require('path') to use this module.
// This module contains utilities for handling and transforming file paths.
// Almost all these methods perform only string transformations.
// The file system is not consulted to check whether paths are valid.
// http://nodejs.org/api/fs.html
path.normalize(p); // Normalize a string path, taking care of '..' and '.' parts.
path.join([path1], [path2], [...]); // Join all arguments together and normalize the resulting path.
path.resolve([from ...], to); // Resolves 'to' to an absolute path.
path.relative(from, to); // Solve the relative path from 'from' to 'to'.
path.dirname(p); // Return the directory name of a path. Similar to the Unix dirname command.
path.basename(p, [ext]); // Return the last portion of a path. Similar to the Unix basename command.
path.extname(p); // Return the extension of the path, from the last '.' to end of string in the last portion of the path.
path.sep; // The platform-specific file separator. '\\' or '/'.
path.delimiter; // The platform-specific path delimiter, ';' or ':'.
// 12. HTTP.
// To use the HTTP server and client one must require('http').
// http://nodejs.org/api/http.html
http.STATUS_CODES; // A collection of all the standard HTTP response status codes, and the short description of each.
http.request(options, [callback]); // This function allows one to transparently issue requests.
http.get(options, [callback]); // Set the method to GET and calls req.end() automatically.
server = http.createServer([requestListener]); // Returns a new web server object. The requestListener is a function which is automatically added to the 'request' event.
server.listen(port, [hostname], [backlog], [callback]); // Begin accepting connections on the specified port and hostname.
server.listen(path, [callback]); // Start a UNIX socket server listening for connections on the given path.
server.listen(handle, [callback]); // The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.
server.close([callback]); // Stops the server from accepting new connections.
server.setTimeout(msecs, callback); // Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.
server.maxHeadersCount; // Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.
server.timeout; // The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.on('request', function (request, response) { }); // Emitted each time there is a request.
server.on('connection', function (socket) { }); // When a new TCP stream is established.
server.on('close', function () { }); // Emitted when the server closes.
server.on('checkContinue', function (request, response) { }); // Emitted each time a request with an http Expect: 100-continue is received.
server.on('connect', function (request, socket, head) { }); // Emitted each time a client requests a http CONNECT method.
server.on('upgrade', function (request, socket, head) { }); // Emitted each time a client requests a http upgrade.
server.on('clientError', function (exception, socket) { }); // If a client connection emits an 'error' event - it will forwarded here.
request.write(chunk, [encoding]); // Sends a chunk of the body.
request.end([data], [encoding]); // Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.
request.abort(); // Aborts a request.
request.setTimeout(timeout, [callback]); // Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
request.setNoDelay([noDelay]); // Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable], [initialDelay]); // Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
request.on('response', function(response) { }); // Emitted when a response is received to this request. This event is emitted only once.
request.on('socket', function(socket) { }); // Emitted after a socket is assigned to this request.
request.on('connect', function(response, socket, head) { }); // Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.
request.on('upgrade', function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
request.on('continue', function() { }); // Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); // This sends a chunk of the response body. If this merthod 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.statusCode; // When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.
response.headersSent; // Boolean (read-only). True if headers were sent, false otherwise.
response.sendDate; // When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
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.
message.httpVersion; // In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server.
message.headers; // The request/response headers object.
message.trailers; // The request/response trailers object. Only populated after the 'end' event.
message.method; // The request method as a string. Read only. Example: 'GET', 'DELETE'.
message.url; // Request URL string. This contains only the URL that is present in the actual HTTP request.
message.statusCode; // The 3-digit HTTP response status code. E.G. 404.
message.socket; // The net.Socket object associated with the connection.
message.setTimeout(msecs, callback); // Calls message.connection.setTimeout(msecs, callback).
// 13. URL.
// This module has utilities for URL resolution and parsing. Call require('url') to use it.
// http://nodejs.org/api/url.html
url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); // Take a URL string, and return an object.
url.format(urlObj); // Take a parsed URL object, and return a formatted URL string.
url.resolve(from, to); // Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
// 14. Query String.
// This module provides utilities for dealing with query strings. Call require('querystring') to use it.
// http://nodejs.org/api/querystring.html
querystring.stringify(obj, [sep], [eq]); // Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.
querystring.parse(str, [sep], [eq], [options]); // Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.
// 15. Assert.
// This module is used for writing unit tests for your applications, you can access it with require('assert').
// http://nodejs.org/api/assert.html
assert.fail(actual, expected, message, operator); // Throws an exception that displays the values for actual and expected separated by the provided operator.
assert(value, message); assert.ok(value, [message]); // Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
assert.equal(actual, expected, [message]); // Tests shallow, coercive equality with the equal comparison operator ( == ).
assert.notEqual(actual, expected, [message]); // Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
assert.deepEqual(actual, expected, [message]); // Tests for deep equality.
assert.notDeepEqual(actual, expected, [message]); // Tests for any deep inequality.
assert.strictEqual(actual, expected, [message]); // Tests strict equality, as determined by the strict equality operator ( === )
assert.notStrictEqual(actual, expected, [message]); // Tests strict non-equality, as determined by the strict not equal operator ( !== )
assert.throws(block, [error], [message]); // Expects block to throw an error. error can be constructor, RegExp or validation function.
assert.doesNotThrow(block, [message]); // Expects block not to throw an error, see assert.throws for details.
assert.ifError(value); // Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
// 16. OS.
// Provides a few basic operating-system related utility functions.
// Use require('os') to access this module.
// 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.
os.type(); // Returns the operating system name.
os.platform(); // Returns the operating system platform.
os.arch(); // Returns the operating system CPU architecture.
os.release(); // Returns the operating system release.
os.uptime(); // Returns the system uptime in seconds.
os.loadavg(); // Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem(); // Returns the total amount of system memory in bytes.
os.freemem(); // Returns the amount of free system memory in bytes.
os.cpus(); // Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).
os.networkInterfaces(); // Get a list of network interfaces.
os.EOL; // A constant defining the appropriate End-of-line marker for the operating system.
// 17. Buffer.
// Buffer is used to dealing with binary data
// Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap
// http://nodejs.org/api/buffer.html
new Buffer(size); // Allocates a new buffer of size octets.
new Buffer(array); // Allocates a new buffer using an array of octets.
new Buffer(str, [encoding]); // Allocates a new buffer containing the given str. encoding defaults to 'utf8'.
Buffer.isEncoding(encoding); // Returns true if the encoding is a valid encoding argument, or false otherwise.
Buffer.isBuffer(obj); // Tests if obj is a Buffer
Buffer.concat(list, [totalLength]); // Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.byteLength(string, [encoding]); // Gives the actual byte length of a string.
buf.write(string, [offset], [length], [encoding]); // Writes string to the buffer at offset using the given encoding
buf.toString([encoding], [start], [end]); // 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).
buf.toJSON(); // Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays
buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]); // Does copy between buffers. The source and target regions can be overlapped
buf.slice([start], [end]); // 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.
buf.fill(value, [offset], [end]); // Fills the buffer with the specified value
buf[index]; // Get and set the octet at index
buf.length; // The size of the buffer in bytes, Note that this is not necessarily the size of the contents
buffer.INSPECT_MAX_BYTES; // How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.
#!/bin/bash
#####################################################
# Name: Bash CheatSheet for Mac OSX
#
# A little overlook of the Bash basics
#
# Usage:
#
# Author: J. Le Coupanec
# Date: 2014/11/04
#####################################################
# 0. Shortcuts.
CTRL+A # move to beginning of line
CTRL+B # moves backward one character
CTRL+C # halts the current command
CTRL+D # deletes one character backward or logs out of current session, similar to exit
CTRL+E # moves to end of line
CTRL+F # moves forward one character
CTRL+G # aborts the current editing command and ring the terminal bell
CTRL+J # same as RETURN
CTRL+K # deletes (kill) forward to end of line
CTRL+L # clears screen and redisplay the line
CTRL+M # same as RETURN
CTRL+N # next line in command history
CTRL+O # same as RETURN, then displays next line in history file
CTRL+P # previous line in command history
CTRL+R # searches backward
CTRL+S # searches forward
CTRL+T # transposes two characters
CTRL+U # kills backward from point to the beginning of line
CTRL+V # makes the next character typed verbatim
CTRL+W # kills the word behind the cursor
CTRL+X # lists the possible filename completefions of the current word
CTRL+Y # retrieves (yank) last item killed
CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background
DELETE # deletes one character backward
!! # repeats the last command
exit # logs out of current session
# 1. Bash Basics.
export # displays all environment variables
echo $SHELL # displays the shell you're using
echo $BASH_VERSION # displays bash version
bash # if you want to use bash (type exit to go back to your normal shell)
whereis bash # finds out where bash is on your system
clear # clears content on window (hide displayed lines)
# 1.1. File Commands.
ls # lists your files
ls -l # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
ls -a # lists all files, including hidden files
ln -s <filename> <link> # creates symbolic link to file
touch <filename> # creates or updates your file
cat > <filename> # places standard input into file
more <filename> # shows the first part of a file (move with space and type q to quit)
head <filename> # outputs the first 10 lines of file
tail <filename> # outputs the last 10 lines of file (useful with -f option)
emacs <filename> # lets you create and edit a file
mv <filename1> <filename2> # moves a file
cp <filename1> <filename2> # copies a file
rm <filename> # removes a file
diff <filename1> <filename2> # compares files, and shows where they differ
wc <filename> # tells you how many lines, words and characters there are in a file
chmod -options <filename> # lets you change the read, write, and execute permissions on your files
gzip <filename> # compresses files
gunzip <filename> # uncompresses files compressed by gzip
gzcat <filename> # lets you look at gzipped file without actually having to gunzip it
lpr <filename> # print the file
lpq # check out the printer queue
lprm <jobnumber> # remove something from the printer queue
genscript # converts plain text files into postscript for printing and gives you some options for formatting
dvips <filename> # print .dvi files (i.e. files produced by LaTeX)
grep <pattern> <filenames> # looks for the string in the files
grep -r <pattern> <dir> # search recursively for pattern in directory
# 1.2. Directory Commands.
mkdir <dirname> # makes a new directory
cd # changes to home
cd <dirname> # changes directory
pwd # tells you where you currently are
# 1.3. SSH, System Info & Network Commands.
ssh user@host # connects to host as user
ssh -p <port> user@host # connects to host on specified port as user
ssh-copy-id user@host # adds your ssh key to host for user to enable a keyed or passwordless login
whoami # returns your username
passwd # lets you change your password
quota -v # shows what your disk quota is
date # shows the current date and time
cal # shows the month's calendar
uptime # shows current uptime
w # displays whois online
finger <user> # displays information about user
uname -a # shows kernel information
man <command> # shows the manual for specified command
df # shows disk usage
du <filename> # shows the disk usage of the files and directories in filename (du -s give only a total)
last <yourUsername> # lists your last logins
ps -u yourusername # lists your processes
kill <PID> # kills (ends) the processes with the ID you gave
killall <processname> # kill all processes with the name
top # displays your currently active processes
bg # lists stopped or background jobs ; resume a stopped job in the background
fg # brings the most recent job in the foreground
fg <job> # brings job to the foreground
ping <host> # pings host and outputs results
whois <domain> # gets whois information for domain
dig <domain> # gets DNS information for domain
dig -x <host> # reverses lookup host
wget <file> # downloads file
# 2. Basic Shell Programming.
# 2.1. Variables.
varname=value # defines a variable
varname=value command # defines a variable to be in the environment of a particular subprocess
echo $varname # checks a variable's value
echo $$ # prints process ID of the current shell
echo $! # prints process ID of the most recently invoked background job
echo $? # displays the exit status of the last command
export VARNAME=value # defines an environment variable (will be available in subprocesses)
array[0] = val # several ways to define an array
array[1] = val
array[2] = val
array=([2]=val [0]=val [1]=val)
array(val val val)
${array[i]} # displays array's value for this index. If no index is supplied, array element 0 is assumed
${#array[i]} # to find out the length of any element in the array
${#array[@]} # to find out how many values there are in the array
declare -a # the variables are treaded as arrays
declare -f # uses funtion names only
declare -F # displays function names without definitions
declare -i # the variables are treaded as integers
declare -r # makes the variables read-only
declare -x # marks the variables for export via the environment
${varname:-word} # if varname exists and isn't null, return its value; otherwise return word
${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value
${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script
${varname:+word} # if varname exists and isn't null, return word; otherwise return null
${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced
${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced
${#varname} # returns the length of the value of the variable as a character string
*(patternlist) # matches zero or more occurences of the given patterns
+(patternlist) # matches one or more occurences of the given patterns
?(patternlist) # matches zero or one occurence of the given patterns
@(patternlist) # matches exactly one of the given patterns
!(patternlist) # matches anything except one of the given patterns
$(UNIX command) # command substitution: runs the command and returns standard output
# 2.2. Functions.
# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.
functname() {
shell commands
}
unset -f functname # deletes a function definition
declare -f # displays all defined functions in your login session
# 2.3. Flow Control.
statement1 && statement2 # and operator
statement1 || statement2 # or operator
-a # and operator inside a test conditional expression
-o # or operator inside a test conditional expression
str1=str2 # str1 matches str2
str1!=str2 # str1 does not match str2
str1<str2 # str1 is less than str2
str1>str2 # str1 is greater than str2
-n str1 # str1 is not null (has length greater than 0)
-z str1 # str1 is null (has length 0)
-a file # file exists
-d file # file exists and is a directory
-e file # file exists; same -a
-f file # file exists and is a regular file (i.e., not a directory or other special type of file)
-r file # you have read permission
-r file # file exists and is not empty
-w file # your have write permission
-x file # you have execute permission on file, or directory search permission if it is a directory
-N file # file was modified since it was last read
-O file # you own file
-G file # file's group ID matches yours (or one of yours, if you are in multiple groups)
file1 -nt file2 # file1 is newer than file2
file1 -ot file2 # file1 is older than file2
-lt # less than
-le # less than or equal
-eq # equal
-ge # greater than or equal
-gt # greater than
-ne # not equal
if condition
then
statements
[elif condition
then statements...]
[else
statements]
fi
for x := 1 to 10 do
begin
statements
end
for name [in list]
do
statements that can use $name
done
for (( initialisation ; ending condition ; update ))
do
statements...
done
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
...
esac
select name [in list]
do
statements that can use $name
done
while condition; do
statements
done
until condition; do
statements
done
# 3. Command-Line Processing Cycle.
# The default order for command lookup is functions, followed by built-ins, with scripts and executables last.
# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`.
command # removes alias and function lookup. Only built-ins and commands found in the search path are executed
builtin # looks up only built-in commands, ignoring functions and commands found in PATH
enable # enables and disables shell built-ins
eval # takes arguments and run them through the command-line processing steps all over again
# 4. Input/Output Redirectors.
cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2
> file # directs standard output to file
< file # takes standard input from file
>> file # directs standard output to file; append to file if it already exists
>|file # forces standard output to file even if noclobber is set
n>|file # forces output to file from file descriptor n even if noclobber is set
<> file # uses file as both standard input and standard output
n<>file # uses file as both input and output for file descriptor n
<<label # here-document
n>file # directs file descriptor n to file
n<file # takes file descriptor n from file
n>>file # directs file description n to file; append to file if it already exists
n>& # duplicates standard output to file descriptor n
n<& # duplicates standard input from file descriptor n
n>&m # file descriptor n is made to be a copy of the output file descriptor
n<&m # file descriptor n is made to be a copy of the input file descriptor
&>file # directs standard output and standard error to file
<&- # closes the standard input
>&- # closes the standard output
n>&- # closes the ouput from file descriptor n
n<&- # closes the input from file descripor n
# 5. Process Handling.
# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.
# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.
# Of course, to interupt a job, type CTRL+C.
myCommand & # runs job in the background and prompts back the shell
jobs # lists all jobs (use with -l to see associated PID)
fg # brings a background job into the foreground
fg %+ # brings most recently invoked background job
fg %- # brings second most recently invoked background job
fg %N # brings job number N
fg %string # brings job whose command begins with string
fg %?string # brings job whose command contains string
kill -l # returns a list of all signals on the system, by name and number
kill PID # terminates process with specified PID
ps # prints a line of information about the current running login shell and any processes running under it
ps -a # selects all processes with a tty except session leaders
trap cmd sig1 sig2 # executes a command when a signal is received by the script
trap "" sig1 sig2 # ignores that signals
trap - sig1 sig2 # resets the action taken when the signal is received to the default
disown <PID|JID> # removes the process from the list of jobs
wait # waits until all background jobs have finished
# 6. Tips and Tricks.
# set an alias
cd; nano .bash_profile
> alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile
# to quickly go to a specific directory
cd; nano .bashrc
> shopt -s cdable_vars
> export websites="/Users/mac/Documents/websites"
source .bashrc
cd websites
# 7. Debugging Shell Programs.
bash -n scriptname # don't run commands; check for syntax errors only
set -o noexec # alternative (set option in script)
bash -v scriptname # echo commands before running them
set -o verbose # alternative (set option in script)
bash -x scriptname # echo commands after command-line processing
set -o xtrace # alternative (set option in script)
trap 'echo $varname' EXIT # useful when you want to print out the values of variables at the point that your script exits
function errtrap {
es=$?
echo "ERROR line $1: Command exited with status $es."
}
trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exists with non-zero status
function dbgtrap {
echo "badvar is $badvar"
}
trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script
# ...section of code in which the problem occurs...
trap - DEBUG # turn off the DEBUG trap
function returntrap {
echo "A return occured"
}
trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing
// XPath CheatSheet
// To test XPath in your Chrome Debugger: $x('/html/body')
// http://www.jittuu.com/2012/2/14/Testing-XPath-In-Chrome/
// 0. XPath Examples.
// More: http://xpath.alephzarro.com/content/cheatsheet.html
'//hr[@class="edge" and position()=1]' // every first hr of 'edge' class
'//table[count(tr)=1 and count(tr/td)=2]' // all tables with 1 row and 2 cols
'//div/form/parent::*' // all divs that have form
'./div/b' // a relative path
'//table[parent::div[@class="pad"] and not(@id)]//a' // any anchor in a table without id, contained in a div of "pad" class
'/html/body/div/*[preceding-sibling::h4]' // give me whatever after h4
'//tr/td[font[@class="head" and text()="TRACK"]]' // all td that has font of a "head" class and text "TRACK"
'./table/tr[last()]' // the last row of a table
'//rdf:Seq/rdf:li/em:id' // using namespaces
'//a/@href' // hrefs of all anchors
'//*[count(*)=3]' // all nodes with 3 children
'//var|//acronym' // all vars and acronyms
// 1. General.
'/html' // whole web page (css: html)
'/html/body' // whole web page body (css: body)
'//text()' // all text nodes of web page
'/html/body/.../.../.../E' // element <E> by absolute reference (css: body > … > … > … > E)
// 2. Tag.
'//E' // element <E> by relative reference (css: E)
'(//E)[2]' // second <E> element anywhere on page
'//img' // image element (css: img)
'//E[@A]' // element <E> with attribute A (css: E[A])
'//E[@A="t"]' // element <E> with attribute A containing text 't' exactly (css: E[A='t'])
'//E[contains(@A,"t")]' // element <E> with attribute A containing text 't' (css: E[A*='t'])
'//E[starts-with(@A, "t")]' // element <E> whose attribute A begins with 't' (css: E[A^='t'])
'//E[ends-with(@A, "t")]' // element <E> whose attribute A ends with 't' (css: E[A$='t'])
'//E[contains(concat(" ", @A, " "), " w ")' // element <E> with attribute A containing word 'w' (css: E[A~='w'])
'//E[matches(@A, "r")]' // element <E> with attribute A matching regex ‘r’
'//E1[@id=I1] | //E2[@id=I2]' // element <E1> with id I1 or element <E2> with id I2 (css: E1#I1, E2#I2)
'//E1[@id=I1 or @id=I2]' // element <E1> with id I1 or id I2 (css: E1#I1, E1#I2)
// 3. Attribute.
'//E/@A' // attribute A of element <E> (css: E@A)
'//*/@A' // attribute A of any element (css: *@A)
'//E[@A2="t"]/@A1' // attribute A1 of element <E> where attribute A2 is 't' exactly (css: E[A2='t']@A1)
'//E[contains(@A,"t")]/@A' // attribute A of element <E> where A contains 't' (css: E[A*='t']@A)
// 4. ID & Name.
'//*[@id="I"]' // element with id I (css: #I)
'//E[@id="I"]' // element <E> with id I (css: E#I)
'//*[@name="N"]' // element with name (css: [name='N'])
'//E[@name="N"]' // element <E> with name (css: E[name='N'])
'//*[@id="X" or @name="X"]' // element with id X or, failing that, a name X
'//*[@name="N"][v+1]' // element with name N & specified 0-based index ‘v’ (css: [name='N']:nth-child(v+1))
'//*[@name="N"][@value="v"]' // element with name N & specified value ‘v’ (css: *[name='N'][value='v’])
// 5. Lang & Class.
'//E[@lang="L" or starts-with(@lang, concat("L", "-"))]' // element <E> is explicitly in language L or subcode (css: E[lang|=L])
'//*[contains(concat(" ", @class, " "), " C ")]' // element with a class C (css: .C)
'//E[contains(concat(" ", @class, " "), " C ")]' // element <E> with a class C (css: E.C)
// 6. Text & Link.
'//*[.="t"]' // element containing text 't' exactly
'//E[contains(text(), "t")]' // element <E> containing text 't' (css: E:contains('t'))
'//a' // link element (css: a)
'//a[.="t"]' // element <a> containing text 't' exactly
'//a[contains(text(), "t")]' // element <a> containing text 't' (css: a:contains('t'))
'//a[@href="url"]' // <a> with target link 'url' (css: a[href='url'])
'//a[.="t"]/@href' // link URL labeled with text 't' exactly
// 7. Parent & Child.
'//E/*[1]' // first child of element <E> (css: E > *:first-child)
'//E[1]' // first <E> child (css: E:first-of-type)
'//E/*[last()]' // last child of element E (css: E *:last-child)
'//E[last()]' // last <E> child (css: E:last-of-type)
'//E[2]' // second <E> child (css: E:nth-of-type(2))
'//*[2][name()="E"]' // second child that is an <E> element (css: E:nth-child(2))
'//E[last()-1]' // second-to-last <E> child (css: E:nth-last-of-type(2))
'//*[last()-1][name()="E"]' // second-to-last child that is an <E> element (css: E:nth-last-child(2))
'//E1/[E2 and not( *[not(self::E2)])]' // element <E1> with only <E2> children
'//E/..' // parent of element <E>
'//*[@id="I"]/.../.../.../E' // descendant <E> of element with id I using specific path (css: #I > … > … > … > E)
'//*[@id="I"]//E' // descendant <E> of element with id I using unspecified path (css: #I E)
'//E[count(*)=0]' // element <E> with no children (E:empty)
'//E[count(*)=1]' // element <E> with an only child
'//E[count(preceding-sibling::*)+count(following-sibling::*)=0]' // element <E> that is an only child (css: E:only-child)
'//E[count(../E) = 1]' // element <E> with no <E> siblings (css: E:only-of-type)
'//E[position() mod N = M + 1]' // every Nth element starting with the (M+1)th (css: E:nth-child(Nn+M))
// 8. Sibling.
'//E2/following-sibling::E1' // element <E1> following some sibling <E2> (css: E2 ~ E1)
'//E2/following-sibling::*[1][name()="E1"]' // element <E1> immediately following sibling <E2> (css: E2 + E1)
'//E2/following-sibling::*[2][name()="E1"]' // element <E1> following sibling <E2> with one intermediary (css: E2 + * + E1)
'//E/following-sibling::*' // sibling element immediately following <E> (css: E + *)
'//E2/preceding-sibling::E1' // element <E1> preceding some sibling <E2>
'//E2/preceding-sibling::*[1][name()="E1"]' // element <E1> immediately preceding sibling <E2>
'//E2/preceding-sibling::*[2][name()="E1"]' // element <E1> preceding sibling <E2> with one intermediary
'//E/preceding-sibling::*[1]' // sibling element immediately preceding <E>
// 9. Table Cell.
'//*[@id="TestTable"]//tr[3]//td[2]' // cell by row and column (e.g. 3rd row, 2nd column) (css: #TestTable tr:nth-child(3) td:nth-child(2))
'//td[preceding-sibling::td="t"]' // cell immediately following cell containing 't' exactly
'td[preceding-sibling::td[contains(.,"t")]]' // cell immediately following cell containing 't' (css: td:contains('t') ~ td)
// 10. Dynamic.
'//E[@disabled]' // user interface element <E> that is disabled (css: E:disabled)
'//*[not(@disabled)]' // user interface element that is enabled (css: E:enabled)
'//*[@checked]' // checkbox (or radio button) that is checked (css: *:checked)
// 11. XPath Functions.
// https://developer.mozilla.org/en-US/docs/Web/XPath/Functions
// 11.1. Conversion.
boolean(expression) // evaluates an expression and returns true or false.
string([object]) // converts the given argument to a string.
number([object]) // converts an object to a number and returns the number.
// 11.2. Math.
ceiling(number) // evaluates a decimal number and returns the smallest integer greater than or equal to the decimal number.
floor(number) // evaluates a decimal number and returns the largest integer less than or equal to the decimal number.
round(decimal) // returns a number that is the nearest integer to the given number.
sum(node-set) // returns a number that is the sum of the numeric values of each node in a given node-set.
// 11.3. Logic.
true() // returns a boolean value of true.
false() // returns boolean false.
not(expression) // evaluates a boolean expression and returns the opposite value.
// 11.4. Node.
lang(string) // determines whether the context node matches the given language and returns boolean true or false.
name([node-set]) // returns a string representing the QName of the first node in a given node-set.
namespace-uri([node-set]) // returns a string representing the namespace URI of the first node in a given node-set.
// 11.5. Context.
count(node-set) // counts the number of nodes in a node-set and returns an integer.
function-available(name) // determines if a given function is available and returns boolean true or false.
last() // returns a number equal to the context size from the expression evaluation context.
position() // returns a number equal to the context position from the expression evaluation context.
// 11.6. String.
contains(haystack-string, needle-string) // determines whether the first argument string contains the second argument string and returns boolean true or false.
concat(string1, string2 [stringn]*) // concatenates two or more strings and returns the resulting string.
normalize-space(string) // strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string.
starts-with(haystack, needle) // checks whether the first string starts with the second string and returns true or false.
string-length([string]) // returns a number equal to the number of characters in a given string.
substring(string, start [length]) // returns a part of a given string.
substring-after(haystack, needle) // returns a string that is the rest of a given string after a given substring.
substring-before(haystack, needle) // returns a string that is the rest of a given string before a given substring.
translate(string, abc, XYZ) // evaluates a string and a set of characters to translate and returns the translated string.
// 12. XPath Axes.
ancestor // indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node.
ancestor-or-self // indicates the context node and all of its ancestors, including the root node.
attribute (@) // indicates the attributes of the context node. Only elements have attributes. This axis can be abbreviated with the at sign (@).
child (/) // indicates the children of the context node. If an XPath expression does not specify an axis, this is understood by default. Since only the root node or element nodes have children, any other use will select nothing.
descendant (//) // indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
descendant-or-self // indicates the context node and all of its descendants. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
following // indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.
following-sibling // indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
parent(..) // indicates the single node that is the parent of the context node. It can be abbreviated as two periods (..).
preceding // indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes.
preceding-sibling // indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.
self (.) // indicates the context node itself. It can be abbreviated as a single period (.).