Node.js Tutorial
Learn Node.js
Run JavaScript on the server — build fast, scalable back-end apps.
Stage 1
01
Getting Started
03
Globals and Process
Stage 2
04
Asynchronous Node
05
Events and Streams
06
The File System
Stage 3
07
HTTP and Servers
08
Working with Data
09
The npm Ecosystem
10
Building a REST API
11
Databases
Stage 4
12
The Event Loop in Depth
13
Streams, Buffers and Events in Depth
14
Authentication and Authorisation
Stage 5
15
Testing
16
Security
17
Caching and Background Work
Stage 6
19
Best Practices and Tooling
20
Advanced and Production
22
Performance and Scaling
Stage 7
23
Containers
24
Kubernetes
Node.js Reference
218 pages · 19 groups · syntax, parameters and worked examples
File System (fs)19
fs.readFile()Reads a whole file asynchronously and hands the contents to a callback.fs.readFileSync()Reads a whole file and returns its contents, blocking the event loop until done.fs.writeFile()Writes data to a file asynchronously, replacing the file if it already exists.fs.writeFileSync()Writes data to a file and blocks until the write completes, replacing any existing contents.fs.appendFile()Appends data to the end of a file, creating the file first if it does not exist.fs.readdir()Lists the names of the entries inside a directory asynchronously.fs.readdirSync()Returns the names of the entries inside a directory, blocking until the listing is complete.fs.existsSync()Tests whether a path exists on the filesystem and returns true or false.fs.stat()Retrieves metadata about a path, such as its size, type and timestamps.fs.mkdir()Creates a directory asynchronously, optionally creating every missing parent along the way.fs.rm()Removes a file or a directory, optionally deleting a whole tree and ignoring missing paths.fs.unlink()Deletes a file or symbolic link asynchronously, failing on directories.fs.rename()Moves or renames a file or directory, replacing the destination if one already exists.fs.access()Tests whether the process can reach a path with the given permissions, failing with an error if not.fs.createReadStream()Opens a file as a readable stream so large files are processed in chunks instead of loaded at once.fs.createWriteStream()Opens a file as a writable stream for incremental writes without holding the whole output in memory.fs.glob()Finds files matching one or more glob patterns, yielding each path as the directory tree is walked.stats.isDirectory()Reports whether a Stats object describes a directory rather than a file or other node type.fs.watch()Watches a file or directory and invokes a listener whenever the operating system reports a change.
File System Promises (fs/promises)12
fsPromises.readFile()Reads an entire file into a string or Buffer and resolves a promise with the contents.fsPromises.writeFile()Writes data to a file, creating it or truncating it first, and resolves when the write completes.fsPromises.appendFile()Appends data to the end of a file, creating the file first if it does not exist.fsPromises.readdir()Lists the entries of a directory, as names or as Dirent objects, optionally recursing into subdirectories.fsPromises.mkdir()Creates a directory, optionally creating every missing parent along the path.fsPromises.rm()Removes a file or directory, with recursive and force options mirroring the rm command.fsPromises.stat()Retrieves metadata for a path: size, timestamps, permissions and whether it is a file or directory.fsPromises.access()Tests whether the process can access a path with the given permissions, rejecting if it cannot.fsPromises.copyFile()Copies a file to a new path, overwriting the destination unless COPYFILE_EXCL is set.fsPromises.open()Opens a file and resolves with a FileHandle for positional reads, writes and streaming.fsPromises.glob()Streams the paths matching one or more glob patterns as an async iterator.fsPromises.watch()Yields filesystem change events for a file or directory as an async iterator.
Path14
path.join()Joins path segments with the platform separator and normalizes the result.path.resolve()Resolves a sequence of path segments into an absolute path.path.basename()Returns the last portion of a path, optionally with a trailing suffix removed.path.dirname()Returns the directory portion of a path, excluding the final component.path.extname()Returns the file extension of a path, from the last dot in the last component.path.normalize()Resolves '..' and '.' segments and collapses repeated separators in a path string.path.relative()Computes the relative path that navigates from one location to another.path.parse()Splits a path string into an object with root, dir, base, name and ext properties.path.format()Builds a path string from an object of root, dir, base, name and ext properties.path.isAbsolute()Reports whether a path is absolute on the current platform.path.sepProvides the platform-specific path segment separator, '/' or a backslash.path.delimiterProvides the platform-specific delimiter used between entries in PATH-style variables.path.posixProvides POSIX-rule implementations of every path method, identical on every platform.path.win32Provides Windows-rule implementations of every path method, identical on every platform.
Operating System (os)12
os.cpus()Returns an array describing each logical CPU core, including its model, speed and cumulative time counters.os.availableParallelism()Returns an estimate of how much parallelism the process can actually use, honouring CPU limits.os.totalmem()Returns the total amount of system memory in bytes as an integer.os.freemem()Returns the amount of free system memory in bytes as an integer.os.platform()Returns the operating system platform string the Node.js binary was compiled for.os.arch()Returns the CPU architecture the Node.js binary was compiled for, such as 'x64' or 'arm64'.os.hostname()Returns the host name of the operating system as a string.os.homedir()Returns the string path of the current user's home directory.os.tmpdir()Returns the operating system's default directory for temporary files as a string.os.userInfo()Returns the effective user's username, uid, gid, shell and home directory from the operating system.os.networkInterfaces()Returns an object of the machine's network interfaces and the addresses assigned to each.os.EOLHolds the platform's end-of-line marker: '\n' on POSIX and '\r\n' on Windows.
URL12
URLParses an absolute or relative URL string into a structured, mutable WHATWG URL object.URL.canParse()Reports whether a string can be parsed as a URL, returning a boolean instead of throwing.url.searchParamsExposes a URL's query string as a live URLSearchParams object that writes changes back to the URL.URLSearchParamsBuilds and parses application/x-www-form-urlencoded query strings from a string, object, or pairs.urlSearchParams.get()Returns the first value for a query parameter name, or null when that name is absent.urlSearchParams.append()Adds another name-value pair to a query string, keeping any existing pairs with the same name.urlSearchParams.toString()Serializes the parameters to a percent-encoded query string, with spaces written as plus signs.url.fileURLToPath()Converts a file: URL into a correctly decoded, platform-specific absolute filesystem path.url.pathToFileURL()Converts a filesystem path into an absolute file: URL with control characters correctly escaped.url.format()Serializes a WHATWG URL to a string, optionally dropping the fragment, query, or credentials.url.parse()Parses a URL string into a legacy URL object; deprecated in favour of the WHATWG URL constructor.url.domainToASCII()Converts an internationalized domain name to its Punycode ASCII form, or '' if it is invalid.
Query Strings5
querystring.parse()Parses a URL query string into a null-prototype object of decoded key/value pairs.querystring.stringify()Serializes an object's own properties into a percent-encoded URL query string.querystring.escape()Percent-encodes a string for use inside a URL query, using the module's own fast encoder.querystring.unescape()Decodes percent-encoded characters in a string without throwing on malformed sequences.querystring.encode()Serializes an object into a URL query string; an alias for querystring.stringify().
Crypto16
crypto.randomUUID()Generates a cryptographically random RFC 4122 version 4 UUID as a 36-character string.crypto.createHash()Creates a Hash object that computes a digest of streamed data using the named algorithm.hash.update()Feeds more data into a Hash object, returning the same object so calls can be chained.hash.digest()Finalizes a Hash and returns the digest of everything passed to update(), as a Buffer or string.crypto.hash()Hashes a single value in one call and returns the digest directly, without a Hash object.crypto.randomBytes()Generates cryptographically strong pseudorandom bytes as a Buffer, synchronously or via callback.crypto.randomInt()Returns a uniformly distributed random integer in [min, max) without modulo bias.crypto.createHmac()Creates an Hmac object that computes a keyed message authentication code over streamed data.crypto.createCipheriv()Creates a Cipher object that encrypts data with a given algorithm, key and initialization vector.crypto.createDecipheriv()Creates a Decipher object that decrypts data using the same algorithm, key and IV used to encrypt it.crypto.scryptSync()Derives a fixed-length key from a password using the deliberately slow, memory-hard scrypt function.crypto.timingSafeEqual()Compares two equal-length buffers in constant time so the result leaks no timing information.crypto.generateKeyPairSync()Generates a matching public and private key pair synchronously, as KeyObjects or encoded PEM/DER.crypto.createSign()Creates a Sign object that hashes data with the given algorithm and signs the digest with a private key.crypto.createVerify()Creates a Verify object that checks a signature against data using a public key, returning true or false.crypto.webcryptoExposes the standard Web Crypto API, giving access to SubtleCrypto and cryptographically strong randomness.
Buffer15
Buffer.from()Creates a Buffer from a string, an array of bytes, an ArrayBuffer or another Buffer.Buffer.alloc()Allocates a new Buffer of a given size, zero-filled or pre-filled with a value you supply.Buffer.allocUnsafe()Allocates a Buffer without zeroing it, trading initialised memory for allocation speed.Buffer.concat()Joins a list of Buffers into a single new Buffer, optionally truncated or padded to a given length.Buffer.isBuffer()Reports whether a value is a Buffer, returning false for strings, Uint8Arrays and plain objects.Buffer.byteLength()Returns how many bytes a string occupies in a given encoding, which is not its character count.Buffer.compare()Compares two Buffers byte by byte and returns -1, 0 or 1 for use in sorting.buf.toString()Decodes a Buffer, or a byte range of it, into a string using the encoding you name.buf.toJSON()Returns the { type: 'Buffer', data: [...] } object that JSON.stringify uses to serialise a Buffer.buf.subarray()Returns a Buffer that views part of the original, sharing its memory rather than copying it.buf.write()Writes a string into an existing Buffer at an offset and returns how many bytes it wrote.buf.indexOf()Finds the first occurrence of a string, byte or Buffer inside a Buffer, or -1 if absent.buf.includes()Tests whether a buffer contains a given string, buffer, or byte value, returning true or false.buf.equals()Compares two buffers byte for byte and returns true when their contents are identical.buf.fill()Overwrites a buffer, or a range within it, with a repeated value and returns the same buffer.
Events11
EventEmitterEmit named events and register listeners for them; the base class most Node.js APIs are built on.emitter.on()Register a listener that runs every time the named event is emitted.emitter.once()Register a listener that runs on the next emit only and then removes itself.emitter.emit()Call every listener registered for an event synchronously, passing along the given arguments.emitter.off()Remove one previously registered listener from an event.emitter.removeAllListeners()Remove every listener for one event, or for all events when called with no argument.emitter.listenerCount()Count how many listeners are registered for an event, optionally for one specific function.emitter.eventNames()List every event name the emitter currently has at least one listener for.emitter.setMaxListeners()Change the listener count at which an emitter starts warning about a possible memory leak.events.once()Await the next emission of an event as a promise that rejects if 'error' fires first.events.on()Turn a repeating emitter event into an async iterator you can consume with for await.
Stream11
stream.ReadableCreate a source stream that produces data on demand for consumers to read.stream.WritableCreate a destination stream that accepts written chunks and handles them.stream.TransformCreate a duplex stream that rewrites each chunk on its way through.stream.Readable.from()Build a readable stream from any array, iterable, or async generator.readable.pipe()Connect a readable stream to a writable one with automatic backpressure.readable.toArray()Collect every chunk of a stream into a single array.writable.write()Write one chunk to a stream and learn whether its buffer is now full.writable.end()Signal that no more data will be written, with an optional final chunk.stream.pipeline()Connect streams end to end, forwarding errors and destroying them all on failure.streamPromises.pipeline()Await a chain of streams that cleans up every stage when one fails.stream.finished()Detect when a stream has ended, errored, or closed prematurely.
Worker Threads6
WorkerRuns a JavaScript file on a separate thread with its own event loop and V8 isolate.isMainThreadTells you whether the current code is running on the main thread or inside a worker.parentPortGives a worker the port it uses to send messages back to the thread that spawned it.workerDataHolds a clone of the data passed to this thread's Worker constructor.MessageChannelCreates a pair of linked ports forming a two-way communication channel between threads.worker.postMessage()Sends a structured-cloned value from the parent thread into a running worker.
Zlib8
zlib.gzipSync()Compresses a buffer or string into gzip format synchronously and returns the result as a Buffer.zlib.gunzipSync()Decompresses gzip-formatted data synchronously and returns the original bytes as a Buffer.zlib.deflateSync()Compresses data synchronously into the raw zlib (DEFLATE) format and returns it as a Buffer.zlib.inflateSync()Decompresses zlib-format (DEFLATE) data synchronously and returns the original bytes as a Buffer.zlib.brotliCompressSync()Compresses data synchronously with Brotli, typically producing smaller output than gzip on text.zlib.brotliDecompressSync()Decompresses Brotli-compressed data synchronously and returns the original bytes as a Buffer.zlib.createGzip()Creates a Transform stream that compresses data written to it into gzip format.zlib.createGunzip()Creates a Transform stream that decompresses gzip data as it flows through.
Readline8
readline.createInterface()Creates an Interface that splits a readable stream into lines and optionally drives a prompt.rl.on('line')Registers a listener called with each complete line the readline interface reads from its input.rl[Symbol.asyncIterator]()Returns an async iterator so a readline interface can be consumed with for await...of.rl.close()Closes a readline interface, releasing its input and output streams and emitting the 'close' event.readlinePromises.createInterface()Creates a readline interface whose question() and prompt helpers return promises instead of taking callbacks.readline.cursorTo()Moves the terminal cursor to an absolute column, and optionally row, on a writable stream.readline.clearLine()Erases part or all of the current terminal line on a writable stream.rl.question()Writes a prompt to the output stream and passes the user's typed answer to a callback.
Assert13
assert.ok()Throws an AssertionError when the given value is falsy, otherwise does nothing.assert.equal()Compares two values with == and throws an AssertionError when they are not loosely equal.assert.strictEqual()Compares two values with Object.is() and throws an AssertionError when they differ.assert.notStrictEqual()Throws an AssertionError when two values are strictly equal under Object.is().assert.deepStrictEqual()Recursively compares two values by structure, type and prototype, throwing when they differ.assert.notDeepStrictEqual()Throws an AssertionError when two values are deeply, strictly equal.assert.partialDeepStrictEqual()Checks that the expected value is a deep subset of the actual value, ignoring extra properties.assert.throws()Runs a function and throws an AssertionError unless it threw an error matching the expectation.assert.rejects()Awaits a promise or async function and fails unless it rejects with a matching error.assert.match()Tests a string against a regular expression and throws an AssertionError when it does not match.assert.fail()Throws an AssertionError unconditionally, with your message or the default 'Failed'.assert.ifError()Throws the given value unless it is null or undefined, for checking callback error arguments.assert.strictExposes the assert module in strict assertion mode, where loose methods compare like their strict twins.
Child Processes7
child_process.spawn()Launch a command in a new process and stream its stdout and stderr back as Node streams.child_process.exec()Run a command through a shell and pass its buffered stdout and stderr to a callback.child_process.execFile()Run an executable directly, without a shell, and buffer its output into a callback.child_process.fork()Start a second Node.js process running a module, connected to the parent by an IPC channel.child_process.execSync()Run a shell command, block until it finishes, and return its stdout.child_process.spawnSync()Run a command synchronously without a shell and get a result object holding status, stdout and stderr.subprocess.on()Listen for a child process's lifecycle events such as 'spawn', 'exit', 'close', 'error' and 'message'.
HTTP9
http.createServer()Creates an http.Server that emits a request event for every incoming HTTP request.server.listen()Binds the server to a port, host, or Unix socket and starts accepting connections.http.request()Issues an outgoing HTTP request and returns a writable ClientRequest stream for the body.http.get()Sends a GET request and calls end() for you, returning the ClientRequest.http.IncomingMessageRepresents an incoming request on the server or a response on the client as a readable stream.response.writeHead()Writes the status line and response headers, returning the response so calls can be chained.http.STATUS_CODESMaps every standard HTTP status code to its short reason phrase.http.METHODSLists every HTTP method name this Node build's parser will accept.http.validateHeaderName()Throws if the given string is not a valid HTTP header name, otherwise returns undefined.
Utilities (util)13
util.promisify()Converts an error-first callback function into one that returns a promise instead.util.callbackify()Converts an async function into one that takes an error-first callback as its last argument.util.format()Builds a string from a printf-style format and its arguments, the way console.log does.util.inspect()Renders any value as the readable debug string Node prints for objects in console.log.util.styleText()Wraps text in ANSI colour codes, returning it unchanged when the target stream cannot show colour.util.parseArgs()Parses command-line arguments into named values and positionals from a declared option spec.util.deprecate()Wraps a function so it prints a one-time deprecation warning to stderr when first called.util.isDeepStrictEqual()Compares two values for deep strict equality and returns a boolean instead of throwing.util.stripVTControlCharacters()Removes ANSI escape sequences from a string, leaving only the visible text.util.parseEnv()Parses the text of a .env file into an object of string environment variables.util.typesProvides reliable type predicates for built-in objects that survive proxies and cross-realm values.util.TextEncoderEncodes a JavaScript string into a Uint8Array of UTF-8 bytes.util.TextDecoderDecodes bytes in a given character encoding into a string, buffering partial characters between chunks.
Process19
process.envReads and writes the environment variables of the running Node.js process as a string-valued object.process.argvReturns the command-line arguments the process was launched with, as an array of strings.process.cwd()Returns the absolute path of the directory the Node.js process is currently working in.process.chdir()Changes the current working directory of the Node.js process to the given path.process.platformIdentifies the operating system the Node.js binary was built for, such as 'linux', 'darwin' or 'win32'.process.archReports the CPU architecture the running Node.js binary was compiled for, such as 'x64' or 'arm64'.process.versionReturns the Node.js version string of the running process, prefixed with 'v'.process.versionsLists the version strings of Node.js and every dependency it was built against, such as V8, libuv and OpenSSL.process.pidReturns the operating system process ID of the current Node.js process.process.memoryUsage()Reports the memory the Node.js process is using, in bytes, broken down by heap, RSS and external allocations.process.hrtime.bigint()Returns a monotonic high-resolution timestamp in nanoseconds as a BigInt, for measuring elapsed time.process.nextTick()Queues a callback to run after the current operation completes, before the event loop continues.process.exit()Terminates the Node.js process immediately with the given exit status code.process.exitCodeSets the status code the process will exit with once the event loop drains naturally.process.stdout.write()Writes raw data to standard output without appending a newline.process.on('exit')Registers a synchronous listener that runs just before the process terminates.process.getBuiltinModule()Loads a Node.js built-in module by id without using require() or import.process.loadEnvFile()Parses a .env file and merges its variables into process.env.process.stdinExposes the readable stream connected to standard input, file descriptor 0.
Timers8
setTimeout()Schedules a callback to run once after a minimum delay in milliseconds.setInterval()Repeatedly calls a function with a fixed delay between each invocation.clearTimeout()Cancels a pending timer created by setTimeout() before its callback runs.clearInterval()Stops a repeating timer created by setInterval() so it fires no further.setImmediate()Schedules a callback to run on the check phase, after the current I/O callbacks complete.timeout.unref()Releases a timer's hold on the event loop so the process can exit before it fires.timersPromises.setTimeout()Returns a promise that fulfills with a value after the given delay, cancellable with an AbortSignal.timersPromises.setInterval()Returns an async iterator that yields a value every delay milliseconds until you break out.
All Node.js reference pages A–Z
A
B
C
crypto.randomUUID()crypto.createHash()crypto.hash()crypto.randomBytes()crypto.randomInt()crypto.createHmac()crypto.createCipheriv()crypto.createDecipheriv()crypto.scryptSync()crypto.timingSafeEqual()crypto.generateKeyPairSync()crypto.createSign()crypto.createVerify()crypto.webcryptochild_process.spawn()child_process.exec()child_process.execFile()child_process.fork()child_process.execSync()child_process.spawnSync()clearTimeout()clearInterval()
E
F
fs.readFile()fs.readFileSync()fs.writeFile()fs.writeFileSync()fs.appendFile()fs.readdir()fs.readdirSync()fs.existsSync()fs.stat()fs.mkdir()fs.rm()fs.unlink()fs.rename()fs.access()fs.createReadStream()fs.createWriteStream()fs.glob()fs.watch()fsPromises.readFile()fsPromises.writeFile()fsPromises.appendFile()fsPromises.readdir()fsPromises.mkdir()fsPromises.rm()fsPromises.stat()fsPromises.access()fsPromises.copyFile()fsPromises.open()fsPromises.glob()fsPromises.watch()
H
O
P
path.join()path.resolve()path.basename()path.dirname()path.extname()path.normalize()path.relative()path.parse()path.format()path.isAbsolute()path.seppath.delimiterpath.posixpath.win32parentPortprocess.envprocess.argvprocess.cwd()process.chdir()process.platformprocess.archprocess.versionprocess.versionsprocess.pidprocess.memoryUsage()process.hrtime.bigint()process.nextTick()process.exit()process.exitCodeprocess.stdout.write()process.on('exit')process.getBuiltinModule()process.loadEnvFile()process.stdin
Q
R
S
U
URLURL.canParse()url.searchParamsURLSearchParamsurlSearchParams.get()urlSearchParams.append()urlSearchParams.toString()url.fileURLToPath()url.pathToFileURL()url.format()url.parse()url.domainToASCII()util.promisify()util.callbackify()util.format()util.inspect()util.styleText()util.parseArgs()util.deprecate()util.isDeepStrictEqual()util.stripVTControlCharacters()util.parseEnv()util.typesutil.TextEncoderutil.TextDecoder