Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Built-in Modules

Node.js Built-in Modules

Node.js built-in modules are core functional modules that come with the Node.js runtime and can be used without additional installation. These modules provide basic system functions such as file operations, network communication, and process management, and are fundamental tools for Node.js development.

Unlike third-party modules that need to be installed via npm, built-in modules can be loaded directly through the require() function, for example:

const

fs

=

require

(

'fs'

)

;

// File system module

const

http

=

require

(

'http'

)

;

// HTTP module


Introduction to Common Built-in Modules

The following is a detailed description and functional overview of the main built-in modules in Node.js.

Module name Description Common Classes/Methods Typical use
fs (File System) File system operations readFile, writeFile, mkdir, readdir, createReadStream, createWriteStream File read/write, directory operations
path Handle file paths join, resolve, dirname, basename, extname Cross-platform path handling
http HTTP server/client createServer, request, get Create a web server/client
https HTTPS server/client createServer, request Create a secure web service
url URL parsing and handling parse, format, URLclass URL parsing and construction
querystring Query string handling parse, stringify Handle URL query parameters
os Operating system information cpus, freemem, totalmem, homedir, hostname Get system information
events Event Handling EventEmitter, on, emit, once Custom event system
stream Stream operations Readable, Writable, Duplex, Transform, pipe Handle data streams
crypto Encryption features createHash, createCipher, createDecipher, randomBytes Encryption/decryption/hashing
zlib Compression/decompression createGzip, createGunzip, createDeflate, createInflate Data compression and decompression
util Utility functions promisify, inherits, format, types Utility functions
child_process Child process management exec, execFile, spawn, fork Create a subprocess
cluster Cluster management fork, isMaster, isWorker Multi-process load balancing
dns Domain name resolution lookup, resolve, reverse Domain name resolution
domain A module for handling errors from multiple asynchronous operations create, run, add It provides a mechanism for grouping multiple different I/O operations and handling their errors uniformly.
net Network operations createServer, connect, Socket TCP server/client
dgram UDP datagrams createSocket, send, bind UDP communication
readline Read line by line createInterface, on('line') Command-line interaction
repl Interactive interpreter start, context Create a REPL environment
vm Virtual machine runInContext, createContext, Script Execute JavaScript code
assert Assertion testing equal, strictEqual, deepEqual, throws Unit test assertions
buffer Binary data processing Buffer, alloc, from, concat Handle binary data
console Console output log, error, time, timeEnd Debug output
timers Timer setTimeout, setInterval, setImmediate, clearTimeout Scheduled Tasks
perf_hooks Performance monitoring performance, PerformanceObserver Performance measurement
worker_threads Worker threads Worker, isMainThread, parentPort Multi-threaded programming

1. fs (File System Module)

fs The module provides APIs for interacting with the file system, supporting both synchronous and asynchronous operations.

Main features:

Example code:

Example

const

fs

=

require

(

'fs'

)

;

// Read a file asynchronously

fs.

readFile

(

'example.txt'

,

'utf8'

,

(

err

,

data

)

=>

{

 

if

(

err

)

throw

err

;

  console.

log

(

data

)

;

}

)

;

// Write to a file synchronously

try

{

  fs.

writeFileSync

(

'output.txt'

,

'Hello Node.js'

)

;

  console.

log

(

'File written successfully'

)

;

}

catch

(

err

)

{

  console.

error

(

err

)

;

}

2. path (Path Module)

path The module provides utility functions for handling file and directory paths and can be used across platforms.

Common methods:

Example code:

Example

const

path

=

require

(

'path'

)

;

const

fullPath

=

path.

join

(

__dirname

,

'files'

,

'example.txt'

)

;

console.

log

(

fullPath

)

;

// Output similar to: /home/user/project/files/example.txt

const

ext

=

path.

extname

(

'index.html'

)

;

console.

log

(

ext

)

;

// Output: .html

3. http (HTTP Module)

http The module allows Node.js to run as an HTTP server or client.

Main features:

Example code: create a simple server

Example

const

http

=

require

(

'http'

)

;

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

  res.

writeHead

(

200

,

{

'Content-Type'

:

'text/plain'

}

)

;

  res.

end

(

'Hello Node.js Server'

)

;

}

)

;

server.

listen

(

3000

,

(

)

=>

{

  console.

log

(

'Server running at http://localhost:3000/'

)

;

}

)

;

4. events (Events Module)

events The module provides an event-driven programming interface and is the foundation of asynchronous programming in Node.js.

Core concepts:

Example code:

Example

const

EventEmitter

=

require

(

'events'

)

;

class

MyEmitter

extends

EventEmitter

{

}

const

myEmitter

=

new

MyEmitter

(

)

;

// Listen for events

myEmitter.

on

(

'event'

,

(

)

=>

{

  console.

log

(

'Event triggered!'

)

;

}

)

;

// Trigger an event

myEmitter.

emit

(

'event'

)

;

5. os (Operating System Module)

os The module provides utility methods and properties related to the operating system.

Common features:

Example code:

Example

const

os

=

require

(

'os'

)

;

console.

log

(

os.

platform

(

)

)

;

// Operating system platform

console.

log

(

os.

totalmem

(

)

)

;

// Total system memory

console.

log

(

os.

freemem

(

)

)

;

// Available system memory

console.

log

(

os.

cpus

(

)

)

;

// CPU information


Other Important Built-in Modules

1. util (Utilities Module)

util The module provides various utility functions, including:

2. crypto (Crypto Module)

crypto The module provides cryptographic features, including:

3. stream (Stream Module)

stream The module is an abstract interface for working with streaming data, and many modules in Node.js are implemented based on streams.

4. child_process (Child Process Module)

child_process The module allows creating and controlling child processes, which can execute system commands or other programs.

5. url (URL Module)

url The module provides tools for URL parsing and formatting.


How to Use Built-in Modules

All built-in modules can be loaded directly through the require() function:

Example

const

moduleName

=

require

(

'module_name'

)

;

Notes:

  1. Module names do not need a path prefix
  2. Module names are case-sensitive
  3. No installation needed; they come with Node.js
  4. Different Node.js versions may include different built-in modules

Advantages of Built-in Modules

  1. High performance: tightly integrated with the Node.js runtime
  2. Stability: rigorously tested and highly reliable
  3. No installation needed: ready to use out of the box
  4. Cross-platform: consistent behavior across different operating systems
  5. Document thoroughly: detailed official documentation