0
0
Node.jsframework~5 mins

Built-in modules overview in Node.js

Choose your learning style9 modes available
Introduction

Built-in modules provide ready-to-use tools in Node.js. They help you do common tasks without installing extra packages.

You want to read or write files on your computer.
You need to create a web server to handle requests.
You want to work with paths and directories easily.
You need to handle data streams for efficient processing.
You want to get information about the operating system.
Syntax
Node.js
import fs from 'node:fs';
import http from 'node:http';

// Use the module functions like fs.readFile or http.createServer

Use import with the node: prefix to load built-in modules in modern Node.js.

Built-in modules do not need installation; they come with Node.js.

Examples
Reads a file and prints its content.
Node.js
import fs from 'node:fs';

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
Creates a simple web server that responds with 'Hello World'.
Node.js
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World');
});

server.listen(3000);
Joins parts of a file path in a safe way.
Node.js
import path from 'node:path';

const fullPath = path.join('/users', 'john', 'docs');
console.log(fullPath);
Sample Program

This program uses the built-in os module to show basic information about your computer's operating system.

Node.js
import os from 'node:os';

console.log('Operating System Info:');
console.log('Platform:', os.platform());
console.log('CPU Count:', os.cpus().length);
console.log('Free Memory (bytes):', os.freemem());
OutputSuccess
Important Notes

Built-in modules cover many areas like file system, networking, streams, and more.

Always check the Node.js documentation for the latest built-in modules and their features.

Using built-in modules helps keep your project lightweight and fast.

Summary

Built-in modules are ready tools included in Node.js for common tasks.

You import them with import and the node: prefix.

They save time and avoid extra installations.