# Miscellanea
docs
to learn
# Event Loop
# Command Line Options
Synopsis
node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments] node debug [script.js | -e "script" | <host>:<port>] … node --v8-options node- options
-v, --version-h, --help-e, --eval "script"— Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in script-p, --print "script"— Identical to-ebut prints the result- more
- options
more on official (opens new window)
# Modules
# Cornerstone
buffer- enable interaction with octet streams in TCP streams, file system operations, and other contexts
- the
Bufferclass implements theUint8Array - The
Bufferclass is a global within Node.js, no need forrequire('buffer').Buffer - Instances of the
Bufferclass are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap - The size of the
Bufferis established when it is created and cannot be resized buffer.Bufferfrom(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer
from(data: any[]): Buffer
from(data: Uint8Array): Buffer
from(str: string, encoding?: string): BuffertoString(encoding?: string, start?: number, end?: number): string- encoding —
'uft8'(default),'ascii','base64','binary','hex', more
- encoding —
string_decoder— decodingBufferwith care to multi-byte UTF-8 and UTF-16 characters- constructor
string_decoder.StringDecoder(encoding?: string): NodeStringDecoderencodingdefaults toutf8
NodeStringDecoder.write(buffer: Buffer): string— Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the Buffer are omitted from the returned string and stored in an internal buffer for the next call towrite()orend()NodeStringDecoder.end(buffer?: Buffer): string— Returns any remaining input stored in the internal buffer- if argument provided, one final call to
write()is performed before returning the remaining input
- if argument provided, one final call to
- constructor
stream— an abstract interface for working with streaming data- Object Mode
- All streams created by Node.js APIs operate exclusively on strings and
Buffer(orUint8Array) objects - stream implementations can work with other types of JavaScript values with the exception of
null
- All streams created by Node.js APIs operate exclusively on strings and
- Buffering
- get —
Writable._writableState.getBuffer()orReadable._readableState.buffer - amount — determined by
Stream.highWaterMark: number, defaults to a total number of bites - buffering — Once the total size of the internal read buffer reaches the threshold specified by
highWaterMark, the stream will temporarily stop reading data from the underlying resource until the data currently buffered can be consumed - duplex — Duplex and Transform streams are both Readable and Writable, each maintain two separate internal buffers used for reading and writing
- get —
- Writable Streams —
stream.Writeable- implementations (some are Duplex streams that implement the Writable interface)
- HTTP requests, on the client
- HTTP responses, on the server
fswrite streamszlibstreamscryptostreams- TCP sockets
- child process stdin
process.stdout,process.stderr
readonlywritableHighWaterMark: numberwritableLength: number
- events
'close'(not all will emit this event, such asprocess.stderr)'drain'— If a call tostream.write(chunk)returnsfalse, the'drain'event will be emitted when it is appropriate to resume writing data to the stream'finish'— after thestream.end()method has been called, and all data has been flushed to the underlying systemon(event: "error", listener: (err: Error) => void): this— an error occurred while writing or piping data (the stream is not closed)on(event: "pipe", listener: (src: Readable) => void): this— emitted when thestream.pipe()method is called on a readable stream, adding this writable to its set of destinationson(event: "unpipe", listener: (src: Readable) => void): this— emitted when thestream.unpipe()method is called on a Readable stream, removing this Writable from its set of destinations, also emitted in case this Writable stream emits an error when a Readable stream pipes into it
write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean
write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean- writes some data to the stream, and calls the supplied callback once the data has been fully handled
- If an error occurs, the callback may or may not be called with the error as its first argument. To reliably detect write errors, add a listener for the
'error'event - return
truewhen the internal buffer is less than thehighWaterMarkafter admitting - If
falseis returned, further attempts to write data to the stream should stop until the'drain'event is emitted - While calling
write()on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (Resident set size)
setDefaultEncoding(encoding: string): this- in object mode will always ignore the
encodingargument
- in object mode will always ignore the
end(cb?: () => void): void
end(chunk: any, cb?: () => void): void
end(chunk: any, encoding?: string, cb?: () => void): void- the optional callback function is attached as a listener for the
'finish'event
- the optional callback function is attached as a listener for the
cork(): void— forces all written data to be buffered in memory, The buffered data will be flushed whenend()oruncork()uncork(): void— flushes all data buffered sincestream.cork()was called- it is recommended that calls to
uncork()be deferred usingprocess.nextTick(). Doing so allows batching of allwrite()calls that occur within a given Node.js event loop phase - If the
cork()method is called multiple times on a stream, the same number of calls touncork()must be called to flush the buffered data
- it is recommended that calls to
destroy(error?: Error): void— Destroy the stream, and emit'error'
- implementations (some are Duplex streams that implement the Writable interface)
- Readable Streams —
stream.Readable- implementations
- HTTP responses, on the client
- HTTP requests, on the server
fsread streamszlibstreamscryptostreams- TCP sockets
- child process stdout and stderr
process.stdin
- two modes
- flowing mode, data is read from the underlying system automatically and provided to an application as quickly as possible using events via the
EventEmitterinterface - paused mode, the
stream.read()method must be called explicitly to read chunks of data from the stream - if in flowing mode and there are no consumers available to handle the data, that data will be lost
- switch to flowing mode
- Adding a
'data'event handler - Calling the
stream.resume()method - Calling the
stream.pipe()method to send the data to a Writable
- Adding a
- switch to pause mode
- If there are no pipe destinations, by calling the
stream.pause()method - If there are pipe destinations, by removing all pipe destinations. Multiple pipe destinations may be removed by calling the
stream.unpipe()method - removing
'data'handler is no use for backwards compatibility
- If there are no pipe destinations, by calling the
- flowing mode, data is read from the underlying system automatically and provided to an application as quickly as possible using events via the
- three states
readable._readableState.flowing = nullreadable._readableState.flowing = falsereadable._readableState.flowing = true
- use one — In general, developers should choose one of the methods of consuming data and should never use multiple methods to consume data from a single stream
readonlyreadableHighWaterMark: numberreadableLength: number
- events
'close'on(event: "data", listener: (chunk: any) => void): this— emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer'end'— emitted when there is no more data to be consumed from the streamon(event: "error", listener: (err: Error) => void): this'readable'— emitted when there is data available to be read from the stream, or the end of the stream data has been reached (read()returnsnull) but before the'end'event is emitted
read(size?: number): any- If
sizebytes are not available to be read,nullwill be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned - only be called on Readable streams operating in paused mode, called automatically in flowing mode
- if returns a chunk of data, a
'data'event will also be emitted - consider
readlinemodule
- If
setEncoding(encoding: string): this— Setting an encoding causes the stream data to be returned asstrings of the specified encoding rather than asBufferobjects when not in object mode- will properly handle multi-byte characters
pause(): this— cause a stream in flowing mode to stop emitting'data'events, switching out of flowing modeisPaused(): booleanresume(): this— switch to flowing modepipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T— switch automatically into flowing mode and push all of its data to the attached Writableoptions.end— defaults totrue, whether end the writer when the reader ends (notprocess.stderrandprocess.stdout)- if the Readable stream emits an error during processing, the Writable destination is not closed automatically
- possible to attach multiple Writable streams to a single Readable stream
unpipe(destination?: NodeJS.WritableStream): this— detaches a Writable stream previously attachedunshift(chunk: any): void— pushes a chunk of data back into the internal buffer- cannot be called after the
'end'event has been emitted or a runtime error will be thrown - Developers using
stream.unshift()often should consider switching to use of a Transform stream instead - best to simply avoid calling while in the process of performing a read
- cannot be called after the
destroy(error?: Error): void— Destroy the stream, and emit'error'push(chunk: any, encoding?: string): boolean— for implementers[Symbol.asyncIterator](): AsyncIterableIterator<any>
- implementations
- Duplex and Transform Streams
stream.Duplex— streams that implement both the Readable and Writable interfaces- TCP sockets
zlibstreamscryptostreams
stream.Transform— Duplex streams where the output is in some way related to the input (Operate on written data, then read the result)zlibstreamscryptostreams
stream.finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void— get notified when a stream is no longer readable, writable or has experienced an error or a premature close event- Especially useful in error handling scenarios where a stream is destroyed prematurely (like an aborted HTTP request), and will not emit
'end'or'finish'
- Especially useful in error handling scenarios where a stream is destroyed prematurely (like an aborted HTTP request), and will not emit
stream.pipeline(...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream>, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream— pipe between streams forwarding errors and properly cleaning up and provide a callback when the pipeline is complete- only the first stream can be
ReadableStream
- only the first stream can be
- Object Mode
readline— provides an interface for reading data from aReadablestream one line at a time- synchronous version
const rl = readline.createInterface({ input: process.stdin }); function noerr_promisify(fun, ...defaults) { return (...arg) => new Promise((resolve) => { fun(...defaults, ...arg, ans => resolve(ans)); }); } const q = noerr_promisify(rl.question.bind(rl), ''); (async () => { const input = await q(); console.log(`resolved: ${input}`); await q().then(console.log); rl.close(); })();
- synchronous version
events- intro — Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") periodically emit named events that cause Function objects ("listeners") to be called
- Synchronous — all of the functions attached to a specific event are called synchronously when an event is emitted
- switch to an asynchronous —
setImmediate()orprocess.nextTick()
- switch to an asynchronous —
EventEmitter— All objects that emit events are instances of theEventEmitterclass- add a listener
EventEmitter.on(event: string | symbol, listener: (...args: any[]) => void): this— allows one or more functions to be attached to named events emitted by the object- Any values returned by the called listeners are ignored and will be discarded
- alias —
EventEmitter.addListener()
EventEmitter.prependListener(event, listener): this— add to the beginning of the listeners array- disposable —
EventEmitter.once(event: string | symbol, listener: (...args: any[]) => void): this - disposable and beginning —
EventEmitter.prependOnceListener(event, listener): this
- remove a listener
EventEmitter.off(...): this— alias ofEventEmitter.removeListener()EventEmitter.removeListener(event: string | symbol, listener: (...args: any[]) => void): this— remove, at most, one instance of a listener from the listener array- need to remove multiple times if registered multiple times to completely remove
EventEmitter.removeAllListeners(event?: string | symbol): this— Removes all listeners, or those of the specified
- emit an event —
EventEmitter.emit(event: string | symbol, ...args: any[]): boolean— allows an arbitrary set of arguments to be passed to the listener functionsfunctioncallbacks —thisis intentionally set to reference theEventEmitterto which the listener is attached- array function callbacks —
thisis{}(to be verified)
- listener event — All EventEmitters emit the event
'newListener'when new listeners are added and'removeListener'when existing listeners are removed'newListener'— before a listener is added to its internal array of listeners- The
'removeListener'event is emitted after the listener is removed - callback arg —
(eventName: string | symbol, listener: Function)
- maximum number of listeners
- not a hard limit. The
EventEmitterinstance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected- The
--trace-warningscommand line flag can be used to display the stack trace for such warnings - The emitted warning can be inspected with
process.on('warning')
- The
EventEmitter.defaultMaxListeners— default maximum number of events can be registered for any single event, defaults to 10EventEmitter.setMaxListeners(n: number): this— set maximum number of events for individualEventEmitterinstanceEventEmitter.getMaxListeners(): number— for individual instance
- not a hard limit. The
- infomation about registered events
EventEmitter.eventNames(): Array<string | symbol>— listing the events for which the emitter has registered listenersEventEmitter.listenerCount(type: string | symbol): number— the number of listeners listening to a specific eventEventEmitter.listeners(event: string | symbol): Function[]— a copy of the array of listeners for a specific eventEventEmitter.rawListeners(event: string | symbol): Function[]— a copy of the array of listeners for the event namedeventName, including any wrappers (such as those created by.once())
module system
- each file is treated as a separate module
- Variables local to the module will be private, because the module is wrapped in a function
(function(exports, require, module, __filename, __dirname) { // Module code actually lives in here }); - When a file is run directly from Node.js,
require.main === module- the entry point of the current application —
require.main.filename(__filename)
- the entry point of the current application —
- extension —
.js,.json,.node(binary) - Folders as Modules
package.json—"name"for package name,"main"for package entry pointindex.jsorindex.nodewill be attempted to load withoutpackage.json
- module scope
__dirname—path.dirname(__filename)__filename— absolute path of the current module fileexports—module.exportsreferencemodulemodule.children— The module objects required by this onemodule.filenamemodule.idmodule.loadedmodule.parentmodule.paths— The search paths for the modulemodule.require()— provides a way to load a module as ifrequire()was called from the original module
require()require.cache— Modules are cached in this object when they are required. By deleting a key value from this object, the nextrequirewill reload the module. Note that this does not apply to native addons, for which reloading will result in an Errorrequire.resolve()— resolve a module in a specified array of pathsrequire.resolve.paths(request: string): string[]— Returns an array containing the paths searched during resolution ofrequestornullif therequeststring references a core module, for examplehttporfs
require('module').builtinModules: string[]— A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third-party module or not
Global Objects
- The following variables may appear to be global but are not. They exist only in the scope of modules
__dirname__filenameexportsmodulerequire()
Buffer,clearImmediate(),clearInterval(),clearTimeout(),console,process,setImmediate(),setInterval(),setTimeout(),URL,URLSearchParamsglobal— The global namespace object- The top-level scope is not the global scope
var somethinginside a Node.js module will be local to that module
- The following variables may appear to be global but are not. They exist only in the scope of modules
Timers — globals
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout— timers phase- Technically, the poll phase controls when timers are executed
setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout— timers phaseNodeJS.Timeoutref(): NodeJS.Timeout— requests that the Node.js event loop not exit so long as theTimeoutis active, done by defaultunref(): NodeJS.Timeout— the activeTimeoutobject will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before theTimeoutobject's callback is invoked- creates an internal timer that will wake the Node.js event loop. Creating too many of these can adversely impact performance
refresh(): NodeJS.Timeout— Sets the timer's start time to the current time, and reschedules the timer
setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate— execute once the pull phase completes (check phase)process.nextTick()— processed after the current operation completes, regardless of the current phase of the event loop- can
ref()andunref()
- Cancelling Timers —
clearTimeout(timeoutId: NodeJS.Timeout): void,clearInterval(intervalId: NodeJS.Timeout): void,clearImmediate(immediateId: NodeJS.Immediate): void- not possible to cancel timers that were created using the promisified variants
# debug
assert- use
const assert = require('assert').strict;for strict mode — legacy mode without.strictis deprecated assert(value: any, message?: string, ...optionalParams: any[]): void- alias of
assert.ok()
- alias of
- use
console— as in browsers- A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr console.Console— class with methods can be used to write to any Node.js streamconst { Console } = require('console');orconst { Console } = console;- constructor:
Console(stdout: WriteableStream, stderr?: WriteableStream) - logging
- A global
Errors
- types — standard JavaScript errors, system errors, user-defined errors, assertions
- all inherits global object
Error, MDN (opens new window) - Class: System Error — typically generated at the syscall level, occur when an application violates an operating system constraint such as attempting to read a file that does not exist or when the user does not have sufficient permissions
error.code: stringerror.errno: number | stringerror.syscall: stringerror.path: stringerror.address: stringerror.port: string
inspector— for debugdebugger
- Inserting the statement
debugger;into the source code of a script will enable a breakpoint at that position in the code - debug commands —
help - watchers command —
watch('my_expression'),unwatch('my_expression')
- Inserting the statement
trace_event— provides a mechanism to centralize tracing information generated by V8, Node core, and userspace code
# net
net— creating stream-based TCP or IPC servers and clientscreateServer(connectionListener?: (socket: Socket) => void): ServercreateServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Servernet.Server- events
on(event: "close", listener: () => void): thison(event: "connection", listener: (socket: Socket) => void): thison(event: "error", listener: (err: Error) => void): thison(event: "listening", listener: () => void): this
listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this— TCP server
listen(path: string, backlog?: number, listeningListener?: Function): this— IPC server
listen(options: ListenOptions, listeningListener?: Function): this
listen(handle: any, backlog?: number, listeningListener?: Function): this
- events
createConnection(options: NetConnectOpts, connectionListener?: Function): Socket
createConnection(port: number, host?: string, connectionListener?: Function): Socket
createConnection(path: string, connectionListener?: Function): Socket- alias —
net.connect() - equivalent —
(new net.Server(...)).connect(...)
- alias —
net.Socket extends stream.Duplex- events
on(event: "close", listener: (had_error: boolean) => void): thison(event: "connect", listener: () => void): thison(event: "data", listener: (data: Buffer) => void): thison(event: "drain", listener: () => void): thison(event: "end", listener: () => void): thison(event: "error", listener: (err: Error) => void): thison(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): thison(event: "timeout", listener: () => void): this
readonly bufferSize: numberreadonly bytesRead: numberreadonly bytesWritten: numberreadonly connecting: booleanreadonly destroyed: booleanreadonly localAddress: stringreadonly localPort: numberreadonly remoteAddress?: stringreadonly remoteFamily?: stringreadonly remotePort?: number
- events
http- The interface is careful to never buffer entire requests or responses — the user is able to stream data
- Keys are lowercased
http.METHODS: string[]— A list of the HTTP methods that are supported by the parserhttp.STATUS_CODES: { [errorCode: number]: string | undefined; [errorCode: string]: string | undefined; }—http.STATUS_CODES[404] === 'Not Found'http.createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server
http.createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server- the
requestListeneris registered to the'request'event ServerOptionsfor extendresandreq
- the
class Server extends net.ServersetTimeout(msecs?: number, callback?: () => void): this
setTimeout(callback: () => void): this— Sets the timeout value for socketsmaxHeadersCount: numbertimeout: numberkeepAliveTimeout: number
class ServerResponse extends OutgoingMessagestatusCode: numberstatusMessage: stringassignSocket(socket: net.Socket): voiddetachSocket(socket: net.Socket): voidwriteContinue(callback?: () => void): voidwriteHead(statusCode: number, headers?: OutgoingHttpHeaders): void
writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void
OutgoingMessage extends stream.Writableupgrading: booleanchunkedEncoding: booleanshouldKeepAlive: booleanuseChunkedEncodingByDefault: booleansendDate: booleanfinished: booleanheadersSent: booleanconnection: net.SocketsetTimeout(msecs: number, callback?: () => void): thissetHeader(name: string, value: number | string | string[]): voidgetHeader(name: string): number | string | string[] | undefinedgetHeaders(): OutgoingHttpHeadersgetHeaderNames(): string[]hasHeader(name: string): booleanremoveHeader(name: string): voidaddTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): voidflushHeaders(): void
class IncomingMessage extends stream.ReadablehttpVersion: stringhttpVersionMajor: numberhttpVersionMinor: numberconnection: net.Socketheaders: IncomingHttpHeaders—{[header: string]: string | string[] | undefined}rawHeaders: string[]trailers: { [key: string]: string | undefined }rawTrailers: string[]method?: stringurl?: stringstatusCode?: numberstatusMessage?: stringsocket: net.Socket- more
http.request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest
http.request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest— HTTP requests from the client agenthttp.get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest
http.get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest— sets the method to GET and callsreq.end()automatically, Since most requests are GET requests without bodieslet globalAgent: Agentclass http.Agent— managing connection persistence and reuse for HTTP clients- maintains a pool of connection sockets, provide
{agent: false}to use a new agent for request - tbc
- maintains a pool of connection sockets, provide
class http.ClientRequest— represents an in-progress request whose header has already been queue, return byhttp.request(),http.get()interface RequestOptions extends ClientRequestArgs { }interface ClientRequestArgs { protocol?: string; host?: string; hostname?: string; family?: number; port?: number | string; defaultPort?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; headers?: OutgoingHttpHeaders; auth?: string; agent?: Agent | boolean; _defaultAgent?: Agent; timeout?: number; // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; }
http2— tbcdgram— an implementation of UDP Datagram socketscreateSocket(type: "udp4" | "udp6", callback?: (msg: Buffer, rinfo: RemoteInfo) => void): SocketcreateSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socketdgram.Socket- events
on(event: "close", listener: () => void): thison(event: "error", listener: (err: Error) => void): thison(event: "listening", listener: () => void): thison(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this
send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void
send(msg: Buffer | string | Uint8Array, offset: number, length: number, port, address?, callback?): voidbind(...): void— listen for datagram messages on a named port and optional address
- events
dnsdns.lookup(hostname: string, options?, callback)— use the underlying operating system facilities to perform name resolution- connect to an actual DNS server to perform name resolution, and that always use the network to perform DNS queries
dns.resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void— Uses the DNS protocol to resolve a hostname into an array of the resource records
https— similar tohttpconst options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(443); // Binding to any port less than 1024 requires root privilegehttps.Server— a subclass oftls.Serverand emits events same ashttp.Server
crypto— provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functionslet salt = Math.round((Date.now() * Math.random())) + ''; let salted = crypto.createHash('sha512').update(salt + password, 'utf8').digest('hex');crypto.getHashes(): string[]createHash(algorithm: string, options?: stream.TransformOptions): HashHash extends NodeJS.ReadWriteStreamupdate(data: string | Buffer | NodeJS.TypedArray | DataView): Hash
update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hashdigest(): Buffer
digest(encoding: HexBase64Latin1Encoding): string— TheHashobject can not be used again
tls— an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL- self-signed certificate — Lets Encrypt (opens new window), SSL.md, OpenSSL
zlib— provides compression functionality implemented using Gzip and Deflate/Inflateconst compress = zlib.createDeflate(); // also zlib.createGzip(); fs.createReadStream(source).pipe(compress).pipe(fs.createWriteStream(dest));- more
querystring— similar toURLSearchParamsin browsers but more general as it allows the customization of delimiterstringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string— produces a URL query string from a given obj by iterating through the object's "own properties"parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery— parses a URL query string (str) into a collection of key and value pairsinterface ParsedUrlQuery { [key: string]: string | string[]; }
escape(str: string): string— defaultStringifyOptions.encodeURIComponentunescape(str: string): string— defaultParseOptions.decodeURIComponentsp:&,eq:=interface StringifyOptions { encodeURIComponent?: Function; }interface ParseOptions { maxKeys?: number; decodeURIComponent?: Function; }
url—url.URLandurl.URLSearchParamsis similar to that in browsers" https: // user : pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash " │ │ │ │ │ hostname │ port │ │ │ │ │ │ │ │ ├──────────────┴──────┤ │ │ │ │ protocol │ │ username │ password │ host │ │ │ │ ├──────────┴──┼──────────┴──────────┼─────────────────────┤ │ │ │ │ origin │ │ origin │ pathname │ search │ hash │ ├─────────────┴─────────────────────┴─────────────────────┴──────────┴────────────────┴───────┤ │ href │ └─────────────────────────────────────────────────────────────────────────────────────────────┘ (all spaces in the "" line should be ignored — they are purely for formatting)url.format(URL: URL, options?: URLFormatOptions): string— a customizable serialization of a URL String representation of a WHATWG URL objecturl.domainToASCII(domain: string): string— Returns the Punycode ASCII serialization of the domain. If domain is an invalid domain, the empty string is returnedurl.domainToUnicode(domain: string): string— Returns the Unicode serialization of the domain. If domain is an invalid domain, the empty string is returnedurl.URL— added to global since v10constructor(input: string, base?: string | URL)— Creates a newURLobject by parsing theinputrelative to thebaseprotocol: stringreadonly origin: stringusername: stringpassword: stringhost: stringhostname: stringport: stringpathname: stringsearch: string— Gets and sets the serialized query portion of the URL, will be percent-encodedhash: stringreadonly searchParams: URLSearchParams— the query parameters of the URLhref: string— equivalent toURL.toString()andURL.toJSON()toString(): string— equivalent to that ofURL.hrefandURL.toJSON()toJSON(): string— equivalent to that ofURL.hrefandURL.toString()
URLSearchParams— container mixin, added to global since v10- the purpose of the
querystringmodule is more general, as it allows the customization of delimiter characters (& and =) constructor()
constructor(init?: URLSearchParams)
constructor(init?: string)— leading?is ignored
constructor(init?: { [key: string]: string | string[] | undefined })
constructor(init?: Iterable<[string, string]> | Array<[string, string]>)append(name: string, value: string): voiddelete(name: string): voidentries(): IterableIterator<[string, string]>forEach(callback: (value: string, name: string, searchParams: this) => void): voidget(name: string): string | nullgetAll(name: string): string[]has(name: string): booleankeys(): IterableIterator<string>set(name: string, value: string): voidsort(): voidtoString(): stringvalues(): IterableIterator<string>[Symbol.iterator](): IterableIterator<[string, string]>
- the purpose of the
# Runtime service
process— aglobalthat provides information about, and control over, the current Node.js process- I/O
- used internally in
console - Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX
process.stderr: Stream—fd2process.stdin: Stream—fd0process.stdout: Stream—fd1
- used internally in
- environment
process.argv: string[]—process.execPath, then the executed file, then other argumentsprocess.argv0: string— original value ofprocess.argv[0]process.chdir(directory: string): voidprocess.cwd(): stringprocess.env— an object containing the user environmentprocess.execArgv— the set of Node.js-specific command-line options passed when the Node.js process was launchedprocess.execPath— the absolute pathname of the executableprocess.version: stringprocess.versions: ProcessVersions— version strings of Node.js and its dependencies
- runtime
process.exit(code?: number): never
- more
- I/O
perf_hooks(experimental) — asPerformancein browserschild_process— spawn child processes in a manner that is similar topopen(3)- “How to fix stdio buffering” (opens new window) and its companion piece “Buffering in standard streams” (opens new window)
child_process.spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptions): ChildProcess- command — console command
- Pipes are established between the parent application and the child process
cluster— allows easy creation of child processes that all share server portsconst cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); }- A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load
- The worker processes are spawned using the
child_process.fork()method, so that they can communicate with the parent via IPC and pass server handles back and forth
worker_threads— provides a way to create multiple environments running on independent threads, and to create message channels between them--experimental-workerflag- useful for performing CPU-intensive JavaScript operations; do not use them for I/O
- unlike child processes or when using the
clustermodule, can also share memory efficiently by transferringArrayBufferinstances or sharingSharedArrayBufferinstances between them
# System and OS
fs— file systemPromises API —
require('fs').promises, refer to docs for methodsAll the methods have asynchronous and synchronous forms
- The asynchronous form always takes a completion callback as its last argument
- no guaranteed ordering when called — chain the callbacks, or
await - the first and typically only argument of a callback is always reserved for an exception,
nullorundefinedwhen resolved
- no guaranteed ordering when called — chain the callbacks, or
- the synchronous form any exceptions are immediately thrown
- Exceptions may be handled using
try/catch,or they may be allowed to bubble up.
- Exceptions may be handled using
- The asynchronous form always takes a completion callback as its last argument
While it is not recommended, most fs functions allow the callback argument to be omitted, in which case a default callback is used that rethrows errors
- To get a trace to the original call site, set the
NODE_DEBUGenvironment variable
- To get a trace to the original call site, set the
hidden file on windows
- On Windows, opening an existing hidden file using the
wflag (either throughfs.openorfs.writeFile) will fail withEPERM - Existing hidden files can be opened for writing with the
r+flag
- On Windows, opening an existing hidden file using the
type PathLike = string | Buffer | URL- WHATWG
URLobject support experimental —file:protocol, tbc
- WHATWG
fd: number— file descriptor, returned byfs.open()watch for changes on a file or a director —
fs.watch()function watch( filename: PathLike, options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, listener?: (event: string, filename: string) => void, ): FSWatcher- listener will be attached to the
'change'event of the returnedFSWatcher - less efficient —
fs.watchFile(...): void,fs.unwatchFile(...): void fs.FSWatcher extends events.EventEmitter- event
'change'— Emitted when something changes in a watched directory or file: callback —(eventType: string, filename: string | Buffer)—eventTypecan bechangeorrename - event
'error'— callback —(error: Error) FSWatcher.close(): void
- event
- listener will be attached to the
fs.access(...): void— Tests a user's permissions for the file or directoryfs.accessSync(...): void- Using
fs.access()to check for the accessibility of a file before calling otherfsmethods is not recommended — introduces a race condition - should open/read/write the file directly and handle the error raised if the file is not accessible
rename — rename(2) (opens new window)
fs.rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): voidfs.renameSync(oldPath: PathLike, newPath: PathLike): void
truncate — truncate(2) (opens new window)
fs.truncate(path: PathLike, len?: number | undefined | null, callback): void— Truncate a file to a specified length,truncate(2)fs.ftruncate(fd: number, len: number | undefined | null, callback): void— ftruncate(2) - Truncate a file to a specified lengthfs.ftruncateSync(fd: number, len?: number | null): voidfs.truncateSync(path: PathLike, len?: number | null): void- extend with null bytes when large
len,lendefault to 0
Change ownership — chown(2) (opens new window)
fs.chown(path: PathLike, uid: number, gid: number, callback): voidfs.chownSync(path: PathLike, uid: number, gid: number): voidfs.fchown(fd: number, uid: number, gid: number, callback): voidfs.fchownSync(fd: number, uid: number, gid: number): voidfs.lchown(path: PathLike, uid: number, gid: number, callback): void
Change permissions — chmod(2) (opens new window)
- modes (opens new window)
fs.chmod(path: PathLike, mode: string | number, callback): voidfs.chmodSync(path: PathLike, mode: string | number): voidfs.fchmod(fd: number, mode: string | number, callback): voidfs.fchmodSync(fd: number, mode: string | number): voidfs.lchmod(path: PathLike, mode: string | number, callback): void— BSD variant, Does not dereference symbolic linksfs.lchmodSync(path: PathLike, mode: string | number): void
get file status — stat(2) (opens new window)
fs.stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): voidfs.statSync(path: PathLike): Statsfs.fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): voidfs.fstatSync(fd: number): Statsfs.lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): voidfs.lstatSync(path: PathLike): Statsclass StatsisFile(): booleanisDirectory(): booleanisBlockDevice(): booleanisCharacterDevice(): booleanisSymbolicLink(): boolean(only valid with fs.lstat())isFIFO(): booleanisSocket(): boolean- coordination —
util.inspect(stats)—dev: numberino: numbermode: numbernlink: numberuid: numbergid: numberrdev: numbersize: numberblksize: numberblocks: numberatimeMs: numbermtimeMs: numberctimeMs: numberbirthtimeMs: numberatime: Datemtime: Datectime: Datebirthtime: Date - a: access, m: modified, c: change
link — link(2) (opens new window), symlink(2) (opens new window), readlink(2) (opens new window), unlink(2) (opens new window)
fs.link(existingPath: PathLike, newPath: PathLike, callback): voidfs.linkSync(existingPath: PathLike, newPath: PathLike): voidfs.symlink(target: PathLike, path: PathLike, callback): void
fs.symlink(target: PathLike, path: PathLike, type: symlink.Type | null, callback): voidfs.symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): voidsymlink.Type = "dir" | "file" | "junction"— only available on Windows (ignored on other platforms), defaults to'file'fs.readlink(...): voidfs.readlinkSync(...): string | Bufferfs.unlink(path: PathLike, callback): voidfs.unlinkSync(path: PathLike): void
path — path(3) (opens new window)
fs.realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void
buffer overloadfs.realpath.native(...): voidfs.realpathSync(path: PathLike, options?): string | Bufferfs.realpathSync(...): ...
dir — rmdir(2) (opens new window), mkdir(2) (opens new window),
mkdtemp, readdir(3) (opens new window)fs.rmdir(path: PathLike, callback): voidfs.rmdirSync(path: PathLike): voidfs.mkdir(path: PathLike, mode: number | string | MakeDirectoryOptions | undefined | null, callback): voidfs.mkdirSync(path: PathLike, mode?: number | string | MakeDirectoryOptions | null): voidfs.mkdtemp(...)fs.mkdtempSync(...)fs.readdir(path, options?, callback: (err, files: string[] | Buffer[]) => void): voidfs.readdirSync(path, options?): string[] | Buffer[]
open and close — open(2) (opens new window), [close(2)]
fs.close(fd: number, callback): voidfs.closeSync(fd: number): voidfs.open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): voidflags—r,w,x,+,a
fs.openSync(path: PathLike, flags: string | number, mode?: string | number | null): number
modify — change timestamps
fs.utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback): voidfs.utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): voidfs.futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback): voidfs.futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void
write and read
function write<TBuffer extends BinaryData>( fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, ): void; function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; /////////////////// function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; /////////////////// function read<TBuffer extends BinaryData>( fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, ): void; function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; function readFile( path: PathLike | number, options: { encoding?: string | null; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void, ): void; function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer;read and write stream
function createReadStream(path: PathLike, options?: string | { flags?: string; encoding?: string; fd?: number; mode?: number; autoClose?: boolean; start?: number; end?: number; highWaterMark?: number; }): ReadStream; ///////////// function createWriteStream(path: PathLike, options?: string | { flags?: string; encoding?: string; fd?: number; mode?: number; autoClose?: boolean; start?: number; }): WriteStream;ReadStream extends stream.Readable- event
(event: "open", listener: (fd: number) => void): this(event: "close", listener: () => void): this(event: "ready", listener: () => void): this— ready to be used. Fires immediately after'open'
ReadStream.bytesRead: number— The number of bytes read so farReadStream.path: string | Buffer
- event
WriteStream extends stream.Writable- event — as
ReadStream WriteStream.bytesRead: numberWriteStream.path: string | Buffer
- event — as
copy file
fs.copyFile(src: PathLike, dest: PathLike, callback): void
fs.copyFile(src: PathLike, dest: PathLike, flags: number, callback): voidfs.copyFileSync(src: PathLike, dest: PathLike, flags?: number): void
more tbc
os— provides a number of operating system-related utility methodshostname(): stringloadavg(): number[]uptime(): numberfreemem(): numbertotalmem(): numbercpus(): CpuInfo[]type(): stringrelease(): stringnetworkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }homedir(): stringuserInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }arch(): stringplatform(): NodeJS.Platformtmpdir(): stringendianness(): "BE" | "LE"const EOL: stringmore
path— utilities for working with file and directory paths┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " / home/user/dir / file .txt " └──────┴──────────────┴──────┴─────┘ ┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " C:\ path\dir \ file .txt " └──────┴──────────────┴──────┴─────┘- when working with Windows file paths —
path.win32 - working with POSIX file paths —
path.posix path.normalize(p: string): string— normalizes the given path, resolving'..'and'.'segments, normalizepath.delimiterpath.join(...paths: string[]): string— Join all arguments together and normalize the resulting pathisAbsolute(path: string): booleanrelative(from: string, to: string): stringdirname(p: string): stringbasename(p: string, ext?: string): stringextname(p: string): stringparse(pathString: string): ParsedPath— get root, dir, base, name, and extformat(pathObject: FormatInputPathObject): string— reverse ofparse()const sep: '\\' | '/'const delimiter: ';' | ':'- more
- when working with Windows file paths —
tty— provides thetty.ReadStreamandtty.WriteStreamclassesWhen Node.js detects that it is being run with a text terminal ("TTY") attached,
process.stdinwill, by default, be initialized as an instance oftty.ReadStreamand bothprocess.stdoutandprocess.stderrwill, by default be instances oftty.WriteStream$ node -p -e "Boolean(process.stdout.isTTY)" true $ node -p -e "Boolean(process.stdout.isTTY)" | cat falsemore
# Node.js utilities
repl— provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications- Design and Features —
repl.start(...)createsrepl.REPLServer, which will act as REPL- input and output may be connected to any
Stream - evaluation can be overridden by passing in an alternative evaluation function when the
repl.REPLServerinstance is created - possible to expose a variable to the REPL explicitly by assigning it to the
REPLServer.contextobject
- input and output may be connected to any
- Commands in REPL —
.,.help.break— When in the process of inputting a multi-line expression, entering the .break command (or pressing the<ctrl>-Ckey combination) will abort further input or processing of that expression.clear— Resets the REPL context to an empty object and clears any multi-line expression currently being input.exit— Close the I/O stream, causing the REPL to exit.help— Show this list of special commands.save— Save the current REPL session to a file:> .save ./file/to/save.js.load— Load a file into the current REPL session.> .load ./file/to/load.js.editor— Enter editor mode (<ctrl>-Dto finish,<ctrl>-Cto cancel)
- Special keys
<ctrl>-C— When pressed once, has the same effect as the.breakcommand. When pressed twice on a blank line, has the same effect as the.exitcommand<ctrl>-D— Has the same effect as the.exitcommand<tab>— When pressed on a blank line, displays global and local(scope) variables. When pressed while entering other input, displays relevant autocompletion options
- variables
- modules available as module name
_— ans
--experimental-repl-await— Enable experimental top-levelawaitkeyword support in REPL- more
- Design and Features —
async_hooksexperimental- provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application
ECMAScript Modules —
--experimental-modulesutilutil.format(format: any, ...param: any[]): string—printf-like%s- String%d- Number (integer or floating point value)%i- Integer%f- Floating point value%j- JSON. Replaced with the string'[Circular]'if the argument contains circular references%o- Object. A string representation of an object with generic JavaScript object formatting. Similar toutil.inspect()with options{ showHidden: true, depth: 4, showProxy: true }. This will show the full object including non-enumerable symbols and properties%O- Object. A string representation of an object with generic JavaScript object formatting. Similar toutil.inspect()without options. This will show the full object not including non-enumerable symbols and properties%%- single percent sign ('%'). This does not consume an argument
util.callbackify(...): Function— Takes anasyncfunction (or a function that returns a Promise) and returns a function following the error-first callback styleutil.promisify(...): Promise— Takes a function following the common error-first callback style, i.e. take callback as the last argument, and returns a version that returns promisesthisis lost if not bound
util.debuglog(key: string): (msg: string, ...param: any[]) => void— create aconsole.error()like function that conditionally writes debug messages tostderrbased on the existence of theNODE_DEBUGenvironment variableutil.deprecate<T extends Function>(fn: T, message: string): T— wraps the given function or class in such a way that it is marked as deprecated- emit a
DeprecationWarningusing theprocess.on('warning')event - By default, this warning will be emitted and printed to
stderrexactly once, the first time it is called - behavior controlled by command line flags and
processproperties
- emit a
util.getSystemErrorName(err: number): string— Returns the string name for a numeric error code that comes from a Node.js API- Common System Errors (opens new window)
- typically
Error.errno: numberas parameter
util.inspect(...): string— returns a string representation of object that is primarily useful for debugging. Additional options may be passed that alter certain aspects of the formatted stringutil.isDeepStrictEqual(val1: any, val2: any): booleanutil.TextDecoder— An implementation of the WHATWG Encoding Standard, support some encodings using the full ICU (opens new window) dataclass TextDecoder { readonly encoding: string; // defaults to 'utf-8' readonly fatal: boolean; // defaults to false readonly ignoreBOM: boolean; // byte order mark, defaults to `false` constructor( encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean } ); decode( input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, options?: { stream?: boolean } // true if additional chunks are expected, defaults to false ): string; }- encodings —
utf-8,utf-16, more
- encodings —
util.TextEncoder— An implementation of the WHATWG Encoding Standard, only support UTF-8 encodingclass TextEncoder { readonly encoding: string; constructor(); encode(input?: string): Uint8Array; }util.types— type checks for different kinds of built-in objects, usually have the overhead of calling into C++, primarily useful for addon developers who prefer to do type checking in JavaScriptutil.types.isXxx(...): boolean
v8— exposes APIs that are specific to the version of V8 built into the Node.js binaryvm— provides APIs for compiling and running code within V8 Virtual Machine contextsC++ addons
N-API — Application Binary Interface (ABI) stable across versions of Node.js
# npm
docs
- official site (opens new window), official site (opens new window)
npm help npmnpm help <term>- package search — npms (opens new window), npm (opens new window),
npm search
npm help <term> [<terms..>]npm install,npm inpm install (with no args, in package dir) npm install [<@scope>/]<name> npm install [<@scope>/]<name>@<tag> npm install [<@scope>/]<name>@<version> npm install [<@scope>/]<name>@<version range> npm install <git-host>:<git-user>/<repo-name> npm install <git repo url> npm install <tarball file> npm install <tarball url> npm install <folder>- common options
[-P|--save-prod|-D|--save-dev|-O|--save-optional][-E|--save-exact][-B|--save-bundle][--no-save][--dry-run]
- With the
--productionflag (or when theNODE_ENVenvironment variable is set to production), npm will not install modules listed indevDependencies - scope — a way of grouping related packages together, and also affect a few things about the way npm treats the package
@types
- more
- common options
npm uninstall ...npm uninstall [<@scope>/]<pkg>[@<version>]... [-S|--save|-D|--save-dev|-O|--save-optional|--no-save] aliases: remove, rm, r, un, unlink- options correspond to
dependencies,devDependencies,optionalDependencies
- options correspond to
npm update [...]npm update [-g] [<pkg>...] aliases: up, upgrade- update npm —
npm install npm -g,npm install npm@latest -g
- update npm —
npm outdated— check the registry to see if any (or, specific) installed packages are currently outdatednpm outdated [[<@scope>/]<pkg> ...]npm listnpm ls [[<@scope>/]<pkg> ...] aliases: list, la, llnpm config,npm c— gets its config settings from the command line, environment variables,npmrcfiles, and in some cases, thepackage.jsonfilenpm config set <key> <value> [-g|--global] # value defaults to true npm config get <key> npm config delete <key> npm config list [-l] [--json] # Show all the config settings, -l also show defaults ############################### --json show the settings in json format npm config edit # --global flag to edit the global config npm get <key> npm set <key> <value> [-g|--global]npmrc- four
- per-project config file (/path/to/my/project/.npmrc)
- per-user config file (~/.npmrc)
- global config file ($PREFIX/etc/npmrc)
- npm builtin config file (/path/to/npm/npmrc)
key = value- Environment variables —
prefix = ${HOME}/.npm-packages - array values —
key[] = "first value",key[] = "second value" - line comment —
;,#
- four
npm link,npm ln— Symlink a package foldernpm link (in package dir) # creates global link npm link [<@scope>/]<pkg>[@<version>] # link-install the package- two step
- First,
npm linkin a package folder will create a symlink in the global folder that links to the package where thenpm linkcommand was executed - Next, in some other location, create a symbolic link from globally-installed
package-nametonode_modules/of the current folder
- First,
- two step in one — specify the package to link-install as a path can be resolved
npm link ../node-redis
- two step
npm initnpm init [--force|-f|--yes|-y|--scope] npm init <@scope> (same as `npx <@scope>/create`) npm init [<@scope>/]<name> (same as `npx [<@scope>/]create-<name>`)package.json- npm doc (opens new window)
- based on the CommonJS module system recommendations (opens new window)
name— The name of the package—requiredversion— The current version conforming to semantic version requirements—requireddescription— The package descriptionkeywords— An array of search termsmaintainers— An array of package maintainers (includes name, email, and website)contributors— An array of package contributors (includes name, email, and website)bugs— The URL where bugs can be submittedlicenses— An array of licensesrepository— The package repositorydependencies— Prerequisite packages and their version numbers
publish
a
directoriesfield inpackage.json"directories" : { "doc" : ".", "test" : "test", "example" : "examples" }npm addusernpm publish
# Popular Node Modules
async— collections and flow controlcommander— Command-Line Magicunderscoreorlodashunit test
mochatapejest,ts-jestalsatianchai-immutable
forever— restarts if crashedloadtest
# Koa
philosophy — middleware
- A Koa application is an object containing an array of middleware functions
- executed in a stack-like manner upon request
hello world
const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello World'; }); app.listen(3000);cascading
- downstream
- upstream —
await next()
settings
app.envdefaulting to the NODE_ENV or "development"app.proxywhen true proxy header fields will be trustedapp.subdomainOffsetoffset of .subdomains to ignore [2]
class ApplicationApplication.listen()—http.Server.listen()
Application.callback()— return callback functionsconst http = require('http'); const https = require('https'); const Koa = require('koa'); const app = new Koa(); http.createServer(app.callback()).listen(3000); // equivalent to app.listen(3000) https.createServer(app.callback()).listen(3001);Application.use()— Add the given middleware function to this applicationApplication.key: KeyGrip | string[]— set signed cookie keys, used when signing cookies withctx.cookies.set('name', 'tobi', { signed: true });Application.context— the prototype from whichctxis created, may add additional properties- error handling
- outputs all errors to
stderrunlessapp.silentistrue, except whenerr.statusis 404 orerr.exposeistrue - custom error-handlingif an error is in the req/res cycle and it is not possible to respond to the client, the
app.on('error', (err, ctx) => { log.error('server error', err, ctx) });Contextinstance is also passed
- outputs all errors to
context
Context.req—http.IncomingMessage— request inhttpContext.res—http.ServerResponse— response inhttp- Bypassing Koa's response handling is not supported. Avoid using the following node properties:
res.statusCoderes.writeHead()res.write()res.end()
- Bypassing Koa's response handling is not supported. Avoid using the following node properties:
Context.state— for frontend useContext.app— Application instance referencectx.cookies.get(name, [options])ctx.cookies.set(name, value, [options])