Node.js Reference
Every Node.js global, core module, class and function in one place: concise, accurate pages with live examples that run on Node 24 LTS, with signatures, options and errors.
Globals and Console
-
globalThisThe global object in Node.js and how it differs from browsers. -
__dirname and __filenameCurrent module location in CommonJS. -
import.metadirname, filename, url and resolve in ES modules. -
require()Loading CommonJS modules, JSON and native addons. -
module and exportsThe CommonJS module object and what it exports. -
console.log()Printing values with format specifiers. -
console.error() and console.warn()Writing to stderr. -
console.table()Printing arrays and objects as tables. -
console.dir()Inspecting objects with depth and color options. -
console.group()Indenting related output. -
console.time()Measuring elapsed time with labels. -
console.count()Counting how often a label runs. -
console.assert()Printing only when a condition is false. -
console.trace()Printing the current stack trace. -
Console classCreating a console bound to custom streams. -
structuredClone()Deep-copying values with the structured clone algorithm. -
queueMicrotask()Scheduling a microtask. -
setTimeout()Running a callback once after a delay. -
setInterval()Running a callback repeatedly. -
setImmediate()Running a callback after the poll phase. -
clearTimeout() and friendsCancelling timers and immediates. -
Timeout objectref(), unref(), refresh() and hasRef(). -
atob() and btoa()Base64 conversion of binary strings. -
TextEncoder and TextDecoderConverting between strings and bytes. -
AbortControllerCancelling operations with signals. -
AbortSignaltimeout(), any() and abort reasons. -
EventTarget and EventThe web-style event API in Node.js. -
DOMExceptionStandard web error type. -
BlobImmutable binary data. -
performanceGlobal high-resolution timer.
process
-
process.argvCommand-line arguments. -
process.envEnvironment variables. -
process.cwd() and chdir()The working directory. -
process.platform and archOperating system and CPU information. -
process.version and versionsNode.js and dependency versions. -
process.pid and ppidProcess identifiers. -
process.titleReading and setting the process title. -
process.execPath and execArgvThe Node binary and its flags. -
process.releaseRelease name and LTS information. -
process.featuresFeature flags such as inspector and typescript. -
process.uptime()Seconds since the process started. -
process.hrtime()High-resolution timestamps. -
process.memoryUsage()Heap and resident memory figures. -
process.cpuUsage() and resourceUsage()CPU time and resource counters. -
process.reportDiagnostic reports. -
process.exit()Ending the process immediately. -
process.exitCodeSetting the exit status without exiting. -
The exit and beforeExit eventsRunning cleanup when the loop empties. -
uncaughtExceptionHandling errors nobody caught. -
unhandledRejectionHandling promises rejected without a handler. -
process.emitWarning()Emitting and handling warnings. -
Signal eventsHandling SIGINT, SIGTERM and others. -
process.kill()Sending signals to processes. -
process.nextTick()Running a callback before other async work. -
process.stdinReading standard input. -
process.stdout and stderrWriting to standard streams, TTY detection. -
process.umask()Default file permission mask. -
process.getuid() and friendsUser and group identities. -
process.abort()Aborting with a core dump. -
process.loadEnvFile()Loading a .env file. -
process.getBuiltinModule()Loading core modules without import. -
process.send() and the message eventMessaging a parent process.
Module Systems
-
import and exportES module syntax in Node.js. -
import()Loading modules dynamically. -
Top-level awaitAwaiting in ES modules. -
require(esm)Loading ES modules from CommonJS. -
Module resolution algorithmHow specifiers become files. -
package.json exportsControlling a package's public entry points. -
package.json importsPrivate # specifiers. -
package.json typeChoosing ESM or CommonJS per package. -
Conditional exportsimport, require, node and default conditions. -
File extensions .mjs, .cjs and .mtsHow Node picks module format. -
require.cacheThe CommonJS module cache. -
require.resolve()Finding the path of a module. -
module.createRequire()Using require inside ES modules. -
module.register()Registering customization hooks. -
module.builtinModulesListing core modules. -
module.enableCompileCache()Caching compiled code between runs. -
module.stripTypeScriptTypes()Removing TypeScript syntax. -
module.findPackageJSON()Locating the nearest package.json.
fs and fs/promises
-
fs.readFile()Reading a whole file. -
fs.writeFile()Writing a whole file. -
fs.appendFile()Appending to a file. -
fs.readFileSync()Synchronous reads. -
fs.writeFileSync()Synchronous writes. -
fs.open() and close()File descriptors. -
fs.read()Reading bytes at a position. -
fs.write()Writing bytes at a position. -
fs.truncate()Resizing a file. -
fs.copyFile()Copying a file. -
fs.cp()Copying directories recursively. -
fs.rename()Moving and renaming. -
fs.unlink()Deleting a file. -
fs.rm()Removing files and directory trees. -
fs.existsSync()Checking whether a path exists. -
fs.access()Checking permissions. -
fs.createReadStream()Streaming file reads. -
fs.createWriteStream()Streaming file writes. -
fs.fsync() and fdatasync()Flushing to disk. -
fs.readv() and writev()Vectored I/O. -
fs.mkdir()Creating directories, recursive option. -
fs.mkdtemp()Creating temporary directories. -
fs.readdir()Listing directories, withFileTypes and recursive. -
fs.opendir()Iterating huge directories. -
fs.rmdir()Removing empty directories. -
fs.stat() and lstat()File metadata. -
fs.StatsSize, times, mode and type checks. -
fs.DirentDirectory entry types. -
fs.chmod()Changing permissions. -
fs.chown()Changing owners. -
fs.utimes()Changing timestamps. -
fs.symlink()Creating symbolic links. -
fs.link()Creating hard links. -
fs.readlink()Reading link targets. -
fs.realpath()Resolving to a canonical path. -
fs.statfs()File system statistics. -
fs.glob()Matching files by pattern. -
fs.watch()Watching for changes. -
fs.watchFile()Polling-based watching. -
fs.constantsAccess, open and copy flags. -
File system flagsr, w, a, wx and related modes. -
FileHandleThe fs/promises file object. -
fsPromises.readFile()Promise-based file reads. -
fsPromises.writeFile()Promise-based file writes. -
fsPromises.open()Opening a FileHandle. -
fsPromises.readdir()Promise-based directory listing. -
fsPromises.rm() and mkdir()Promise-based tree operations. -
fsPromises.watch()Async-iterable file watching.
path, os and url
-
path.join()Joining segments and normalizing. -
path.resolve()Building absolute paths. -
path.normalize()Collapsing . and .. segments. -
path.basename()The last path segment. -
path.dirname()The directory portion. -
path.extname()The file extension. -
path.parse() and format()Splitting and rebuilding paths. -
path.relative()Relative path between two paths. -
path.isAbsolute()Testing for absolute paths. -
path.matchesGlob()Matching a path against a glob. -
path.posix and path.win32Platform-specific path rules. -
path.sep and delimiterSeparators by platform. -
os.cpus()CPU core details. -
os.availableParallelism()Suggested worker count. -
os.totalmem() and freemem()Memory figures. -
os.hostname()The machine name. -
os.homedir() and tmpdir()Well-known directories. -
os.platform() and type()Operating system identification. -
os.networkInterfaces()Network addresses. -
os.userInfo()Current user details. -
os.uptime() and loadavg()System uptime and load. -
os.EOL and constantsLine endings, signal and errno constants. -
URLParsing and building URLs. -
URLSearchParamsWorking with query strings. -
URLPatternMatching URLs against patterns. -
fileURLToPath()Converting file URLs to paths. -
pathToFileURL()Converting paths to file URLs. -
URL.canParse()Validating without throwing. -
URL.parse()Parsing that returns null on failure. -
url.format() and domainToASCII()Formatting and IDN helpers. -
url.parse() (legacy)The deprecated parser and its risks. -
querystring moduleLegacy query string parsing.
Buffers and Encoding
-
BufferFixed-size binary data. -
Buffer.from()Creating buffers from strings, arrays and buffers. -
Buffer.alloc()Zero-filled buffers. -
Buffer.allocUnsafe()Uninitialized buffers and pool behavior. -
Buffer.concat()Joining buffers. -
Buffer.compare() and equals()Comparing bytes. -
Buffer.byteLength()Bytes needed for a string. -
Buffer.isBuffer()Type checks. -
buf.toString()Decoding to text. -
buf.subarray()Views onto the same memory. -
buf.copy()Copying between buffers. -
buf.fill()Filling with a value. -
buf.indexOf() and includes()Searching in buffers. -
buf.readUInt32LE() and friendsReading integers. -
buf.writeUInt32LE() and friendsWriting integers. -
buf.readDoubleBE() and floatsReading and writing floating point. -
buf.swap16() and swap32()Byte-order swapping. -
buf.toJSON()JSON form of a buffer. -
Buffer encodingsutf8, hex, base64, base64url, latin1 and more. -
buffer.transcode()Converting between encodings. -
buffer.isUtf8() and isAscii()Validating encodings. -
FileA Blob with a name and modified time. -
ArrayBuffer and SharedArrayBuffer in NodeMemory shared with buffers and threads. -
StringDecoderDecoding multi-byte characters across chunks.
Events and Timers
-
EventEmitterThe publish and subscribe class behind most of Node. -
emitter.on()Adding listeners. -
emitter.once()One-time listeners. -
emitter.emit()Triggering events. -
emitter.off()Removing listeners. -
emitter.prependListener()Controlling listener order. -
emitter.listeners() and listenerCount()Inspecting listeners. -
setMaxListeners()The leak warning threshold. -
events.once()Awaiting an event as a promise. -
events.on()Async-iterating events. -
events.getEventListeners()Listing listeners, including EventTarget. -
The error eventWhy unhandled error events throw. -
captureRejectionsRouting async listener failures. -
EventEmitterAsyncResourceEmitters with async context. -
timers/promises setTimeout()Awaitable delays. -
timers/promises setInterval()Async-iterable ticks. -
timers/promises setImmediate()Awaitable immediates. -
scheduler.wait() and yield()Cooperative scheduling. -
Timers versus nextTick versus immediatesExecution order in practice.
Streams and readline
-
stream.ReadableSources of data. -
stream.WritableDestinations for data. -
stream.DuplexReadable and writable in one. -
stream.TransformModifying data in flight. -
stream.PassThroughA transform that changes nothing. -
Readable.from()Streams from iterables. -
readable.read()Pulling data in paused mode. -
readable.pipe()Connecting streams. -
readable.pause() and resume()Flow control. -
readable.destroy()Tearing a stream down. -
readable.setEncoding()Receiving strings. -
Async iteration of streamsfor await over a Readable. -
readable.map(), filter() and moreStream operators. -
readable.toArray()Collecting a stream. -
writable.write()Writing with backpressure signals. -
writable.end()Finishing a stream. -
writable.cork()Batching writes. -
Stream eventsdata, end, close, drain, finish and error. -
highWaterMarkBuffer size and backpressure. -
Object modeStreaming objects instead of bytes. -
stream.pipeline()Connecting streams with error handling. -
stream.finished()Detecting completion. -
stream.compose()Joining streams into one. -
stream.addAbortSignal()Cancelling streams. -
stream/promisesPromise versions of pipeline and finished. -
ReadableStreamThe web streams API. -
WritableStreamWeb stream sinks. -
TransformStreamWeb stream transformers. -
CompressionStreamCompressing web streams. -
TextDecoderStreamDecoding streams of text. -
Readable.toWeb() and fromWeb()Converting between stream APIs. -
stream/consumerstext(), json(), buffer() and blob(). -
readline.createInterface()Reading input line by line. -
rl.question()Prompting for input. -
The line and close eventsHandling lines as they arrive. -
Async iteration of linesfor await over input. -
readline/promisesPromise-based prompts. -
readline.cursorTo() and clearLine()Moving the cursor. -
readline.emitKeypressEvents()Capturing individual keys. -
tty moduleisatty(), columns and raw mode. -
util.styleText()Coloring terminal output. -
util.stripVTControlCharacters()Removing ANSI codes.
HTTP, HTTPS, net, TLS, dgram and dns
-
http.createServer()Creating a server. -
http.ServerListening, closing and server options. -
http.IncomingMessageThe request on a server, the response on a client. -
http.ServerResponseWriting responses. -
res.writeHead()Status and headers. -
res.end()Finishing a response. -
res.setHeader()Setting headers one at a time. -
res.writeEarlyHints()Sending 103 responses. -
http.request()Making client requests. -
http.get()Simple GET requests. -
http.ClientRequestClient request object and events. -
http.AgentConnection pooling and keep-alive. -
http.METHODS and STATUS_CODESLookup tables. -
http.validateHeaderName()Header validation helpers. -
Server timeoutsheadersTimeout, requestTimeout and keepAliveTimeout. -
The upgrade eventSwitching protocols for WebSockets. -
The connect eventHTTP proxy tunneling. -
https.createServer()HTTPS servers with certificates. -
https.request()HTTPS clients and TLS options. -
http2.createServer()HTTP/2 servers. -
http2.connect()HTTP/2 clients and streams. -
net.createServer()TCP servers. -
net.createConnection()TCP clients. -
net.SocketDuplex socket streams. -
net.ServerListening and connection events. -
net.isIP()Validating IP addresses. -
net.BlockListFiltering addresses and ranges. -
Happy Eyeballs optionsautoSelectFamily for dual-stack connects. -
Unix domain sockets and named pipesLocal IPC with net. -
tls.connect()TLS client connections. -
tls.createServer()TLS servers. -
tls.TLSSocketCertificates and protocol details. -
dgram.createSocket()UDP sockets. -
socket.send()Sending datagrams. -
Broadcast and multicastUDP group communication. -
dns.lookup()Resolving with the OS resolver. -
dns.resolve()Querying DNS records. -
dns.reverse()Reverse lookups. -
dns.ResolverCustom resolvers and servers. -
dns/promisesPromise-based DNS. -
dns.setDefaultResultOrder()IPv4 versus IPv6 preference.
Web APIs in Node.js
-
fetch()HTTP requests with the web API. -
HeadersReading and building HTTP headers. -
RequestRequest objects. -
ResponseResponse objects, json(), text() and body streaming. -
FormDataBuilding multipart bodies. -
WebSocketThe built-in WebSocket client. -
CloseEvent and MessageEventWebSocket event types. -
BroadcastChannelMessaging between threads. -
MessageChannel and MessagePortTwo-way thread messaging. -
crypto.subtleThe Web Crypto API. -
crypto.getRandomValues()Random bytes on the global crypto. -
crypto.randomUUID()Version 4 UUIDs. -
PerformanceObserverObserving performance entries. -
performance.mark() and measure()User timing. -
navigatorhardwareConcurrency, language and userAgent. -
undiciThe engine behind fetch, Agent and MockAgent. -
fetch versus http.requestChoosing a client.
crypto
-
crypto.createHash()SHA-2, SHA-3 and other digests. -
crypto.hash()One-shot hashing. -
crypto.createHmac()Keyed hashes. -
crypto.randomBytes()Secure random bytes. -
crypto.randomInt()Secure random integers. -
crypto.randomFill()Filling buffers with random data. -
crypto.scrypt()Password hashing with scrypt. -
crypto.pbkdf2()Key derivation. -
crypto.hkdf()Expanding key material. -
crypto.timingSafeEqual()Constant-time comparison. -
crypto.createCipheriv()Symmetric encryption. -
crypto.createDecipheriv()Symmetric decryption. -
AES-GCM authenticated encryptionAuth tags and nonces. -
crypto.generateKeyPair()RSA, EC and Ed25519 keys. -
crypto.sign() and verify()Digital signatures. -
crypto.diffieHellman() and ECDHKey agreement. -
crypto.publicEncrypt()Asymmetric encryption. -
KeyObjectKey handles and exports. -
X509CertificateInspecting certificates. -
crypto.getHashes() and getCiphers()Listing algorithms. -
Web Crypto algorithmssubtle.digest, encrypt, sign and deriveKey. -
zlib.gzip() and gunzip()Gzip in memory. -
zlib.deflate() and inflate()Deflate streams and buffers. -
zlib.brotliCompress()Brotli compression. -
zlib.zstdCompress()Zstandard compression. -
zlib.createGzip()Streaming compression. -
zlib.createGunzip()Streaming decompression. -
zlib optionsLevels, windowBits, chunk size and flush modes. -
zlib.crc32()Computing checksums. -
Decompression bombsmaxOutputLength and safe limits.
child_process, worker_threads and cluster
-
child_process.spawn()Starting a process with streamed output. -
child_process.exec()Running a shell command and buffering output. -
child_process.execFile()Running a binary without a shell. -
child_process.fork()Starting another Node.js process with IPC. -
child_process.spawnSync()Blocking process execution. -
child_process.execSync()Blocking shell commands. -
ChildProcessEvents, stdio and kill(). -
stdio optionspipe, inherit, ignore and file descriptors. -
IPC messagingsend() and message between processes. -
Detached processesRunning independently of the parent. -
Shell injectionWhy exec with user input is dangerous. -
WorkerRunning JavaScript in another thread. -
isMainThread and parentPortCoordinating inside workers. -
workerDataPassing startup data. -
Transferring and sharing memoryTransfer lists and SharedArrayBuffer. -
Atomicswait, notify, add and compareExchange. -
setEnvironmentData()Data shared with new workers. -
resourceLimitsConstraining worker memory. -
Worker poolsReusing workers for tasks. -
receiveMessageOnPort()Synchronous message reads. -
cluster.fork()Starting workers. -
cluster.isPrimaryDetecting the primary process. -
Cluster schedulingRound-robin and shared handles. -
cluster.disconnect()Graceful worker shutdown.
util, assert and the Test Runner
-
util.promisify()Converting callbacks to promises. -
util.callbackify()Converting promises to callbacks. -
util.inspect()Formatting objects for display. -
util.format()printf-style formatting. -
util.deprecate()Marking functions deprecated. -
util.inherits()Legacy inheritance helper. -
util.isDeepStrictEqual()Deep equality. -
util.parseArgs()Parsing command-line arguments. -
util.parseEnv()Parsing .env content. -
util.typesReliable type checks. -
util.debuglog()Conditional debug output with NODE_DEBUG. -
util.getSystemErrorName()Mapping errno values to names. -
util.MIMETypeParsing MIME types. -
util.diff()Comparing arrays and strings. -
util.inspect.customCustomizing console output of a class. -
assert() and assert.ok()Basic truthiness checks. -
assert.strictEqual()Strict equality. -
assert.deepStrictEqual()Deep comparison. -
assert.throws()Expecting synchronous errors. -
assert.rejects()Expecting rejected promises. -
assert.match()Regular expression checks. -
assert.partialDeepStrictEqual()Subset comparison. -
AssertionErrorError properties and diffs. -
assert/strictStrict mode by default. -
test()Defining a test. -
describe() and it()Grouping tests. -
before(), after(), beforeEach() and afterEach()Setup and teardown. -
SubtestsNested tests with the test context. -
skip, todo and onlyControlling which tests run. -
mock.fn()Function mocks and call tracking. -
mock.method()Replacing object methods. -
mock.module()Mocking imports. -
mock.timersFaking setTimeout and Date. -
Snapshot testingassert.snapshot and update flags. -
run()Running tests programmatically. -
Test reportersspec, tap, dot, junit and lcov. -
Test coverageBuilt-in coverage and thresholds. -
Test concurrencyParallel files and per-suite concurrency.
node:sqlite and Runtime Services
-
DatabaseSyncOpening a database. -
database.exec()Running SQL statements. -
database.prepare()Prepared statements. -
statement.run()Executing writes. -
statement.get() and all()Reading rows. -
statement.iterate()Streaming rows. -
Named and positional parametersBinding values safely. -
SQLite value typesBigInt, Buffer and null mapping. -
TransactionsBEGIN, COMMIT and ROLLBACK patterns. -
database.function()Custom SQL functions. -
database.aggregate()Custom aggregates. -
sqlite.backup()Copying databases. -
Sessions and changesetsTracking row changes. -
performance.now()Monotonic milliseconds. -
performance.timeOriginAbsolute start time. -
performance.timerify()Timing function calls. -
createHistogram()Recording latency distributions. -
monitorEventLoopDelay()Measuring event loop lag. -
performance.eventLoopUtilization()Measuring how busy the loop is. -
AsyncLocalStorageContext that follows async calls. -
AsyncResourceContext for custom async sources. -
async_hooks.createHook()Low-level async tracking. -
executionAsyncId()Async call identifiers. -
vm.runInNewContext()Evaluating code in a new context. -
vm.ScriptCompiling code once. -
vm.compileFunction()Compiling function bodies. -
vm is not a sandboxWhy it cannot run untrusted code. -
v8.getHeapStatistics()Heap limits and usage. -
v8.writeHeapSnapshot()Capturing heap snapshots. -
v8.serialize()Binary structured serialization. -
v8.getHeapSpaceStatistics()Per-space heap numbers. -
diagnostics_channelPublishing and subscribing to diagnostic events. -
TracingChannelTracing async operations. -
repl.start()Embedding a REPL.
CLI Flags
-
node fileRunning files, stdin and modules. -
-e and -pEvaluating code from the command line. -
--checkSyntax checking without running. -
--watch and --watch-pathRestarting on file changes. -
--testRunning the test runner. -
--require and --importPreloading modules. -
--env-fileLoading environment files. -
--inspect and --inspect-brkDebugging with DevTools. -
--max-old-space-sizeSetting the heap limit. -
--stack-trace-limit and --enable-source-mapsBetter stack traces. -
--conditionsCustom export conditions. -
--experimental flagsOpting into experimental features. -
--experimental-strip-typesRunning TypeScript files. -
--permissionThe permission model flags. -
--trace-warnings and --trace-deprecationLocating warnings. -
--cpu-prof and --heap-profProfiling output files. -
--disable-warningSilencing specific warnings. -
--v8-options and --expose-gcV8 flags. -
NODE_ENVConventions and effects. -
NODE_OPTIONSPassing flags through the environment. -
NODE_PATHExtra module search paths. -
NODE_DEBUGDebug logging for core modules. -
NODE_EXTRA_CA_CERTSTrusting extra certificates. -
UV_THREADPOOL_SIZESizing libuv's thread pool. -
NO_COLOR and FORCE_COLORControlling colored output. -
TZSetting the time zone. -
NODE_USE_ENV_PROXYProxy settings for http and https. -
NODE_TLS_REJECT_UNAUTHORIZEDWhy disabling TLS checks is dangerous.
Concepts and Pitfalls
-
Event loop phasesTimers, poll, check and close callbacks. -
The libuv thread poolWhat runs off the main thread. -
Blocking the event loopSymptoms and fixes. -
Error-first callbacksThe Node callback convention. -
Callback, promise and sync APIsThe three flavors of core APIs. -
Node.js error codesENOENT, EADDRINUSE, ERR_ codes and more. -
System errorserrno, syscall and path properties. -
BackpressureWhy streams need flow control. -
Memory leaksCommon causes and how to find them. -
Unhandled errorsRejections, exceptions and exit behavior. -
Graceful shutdownClosing servers and connections cleanly. -
Security checklistPaths, input, dependencies and secrets. -
Path traversalSafely joining user-provided paths. -
ESM versus CommonJSDifferences and migration tips. -
Release lines and LTSVersions, support and upgrade policy. -
Stability indexStable, experimental and deprecated APIs. -
The node: prefixWhy to import core modules with node:. -
Sync versus async APIsWhen synchronous calls are fine. -
Cross-platform pitfallsPaths, line endings, signals and permissions. -
Testing HTTP serversPort 0, fetch and clean shutdown. -
Modern Node featuresBuilt-in fetch, test runner, watch and TypeScript. -
Node versus browser APIsShared globals and differences.
Không có kết quả nào khớp với “”. Hãy thử tìm kiếm trên trang.
Không có kết quả nào khớp với “”. Hãy thử tìm kiếm trên trang.