Common built-in APIs in Nodejs

muthu raja - Oct 23 - - Dev Community

Node.js offers a wide variety of built-in APIs, which are essential for server-side operations, file handling, networking, and other tasks. Below is a comprehensive list of the key Node.js built-in APIs:

  1. Global Objects
  2. File System (fs) API
  3. HTTP/HTTPS API
  4. Path API
  5. OS API
  6. Events API
  7. Streams API
  8. Buffer API
  9. Timers API
  10. Crypto API
  11. Child Processes API
  12. Process API
  13. URL API

1. Global Objects

  • global
  • process
  • console
  • setTimeout()
  • clearTimeout()
  • setInterval()
  • clearInterval()
  • setImmediate()
  • clearImmediate()
  • queueMicrotask()

2. File System (fs) API
The fs module in Node.js allows you to interact with the file system for reading, writing, and managing files and directories.

Example: Reading a file asynchronously

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode

3. HTTP/HTTPS API
Node.js provides the http and https modules to create web servers, handle HTTP requests, and make HTTP calls.

Example: Creating a simple HTTP server

const http = require('http');

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

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});
Enter fullscreen mode Exit fullscreen mode

4. Path API
The path module provides utilities for working with file and directory paths.

Example: Joining and resolving file paths

const path = require('path');

const fullPath = path.join(__dirname, 'folder', 'file.txt');
console.log(fullPath); // Outputs the full path to file.txt
Enter fullscreen mode Exit fullscreen mode

5. OS API
The os module provides operating system-related utility functions, allowing you to get information about the system.

Example: Getting information about the system

const os = require('os');

console.log('Platform:', os.platform());
console.log('Architecture:', os.arch());
console.log('Total memory:', os.totalmem());
console.log('Free memory:', os.freemem());
Enter fullscreen mode Exit fullscreen mode

6. Events API
The events module provides an EventEmitter class that allows you to create, listen for, and emit custom events.

Example: Creating and emitting events

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('event', () => {
  console.log('An event occurred!');
});

emitter.emit('event'); // Triggers the event listener
Enter fullscreen mode Exit fullscreen mode

7. Streams API
Streams are used in Node.js to handle reading and writing of data in chunks, useful for handling large files or data streams like HTTP requests and responses. The stream module is built into Node.js.

Example: Reading a file as a stream

const fs = require('fs');

const readStream = fs.createReadStream('example.txt');
readStream.on('data', (chunk) => {
  console.log('Received chunk:', chunk);
});
Enter fullscreen mode Exit fullscreen mode

8. Buffer API
The Buffer class in Node.js is used to handle binary data. It's especially useful for working with streams or data that is not in string format (e.g., raw files or network packets).

Example: Creating a buffer and writing to it

const buffer = Buffer.from('Hello World');
console.log(buffer); // Outputs the buffer containing binary data
Enter fullscreen mode Exit fullscreen mode

9. Timers API
Node.js provides timers similar to the browser’s setTimeout and setInterval functions. These are part of the Node.js runtime and are used to execute code after a delay or at regular intervals.

Example: Using setTimeout to delay a function call

setTimeout(() => {
  console.log('Executed after 1 second');
}, 1000);
Enter fullscreen mode Exit fullscreen mode

10. Crypto API
The crypto module provides cryptographic functions for hashing, encryption, and decryption.

Example: Generating a SHA-256 hash

const crypto = require('crypto');

const hash = crypto.createHash('sha256').update('password').digest('hex');
console.log(hash); // Outputs the SHA-256 hash of 'password'
Enter fullscreen mode Exit fullscreen mode

11. Child Processes API
The child_process module allows you to spawn new processes from your Node.js application. This is useful for executing system commands or running external programs.

Example: Spawning a new process to run a system command

const { exec } = require('child_process');

exec('ls', (err, stdout, stderr) => {
  if (err) {
    console.error('Error:', err);
    return;
  }
  console.log('Output:', stdout);
});
Enter fullscreen mode Exit fullscreen mode

12. Process API
The process object is a global object that provides information about the current Node.js process and allows interaction with it.

Example: Accessing command-line arguments

console.log('Command-line arguments:', process.argv);
Enter fullscreen mode Exit fullscreen mode

13. URL API
The url module provides utilities for URL resolution and parsing.
Example: Parsing a URL

const url = require('url');

const myUrl = new URL('https://www.example.com:8080/path?name=foo#bar');
console.log(myUrl.hostname); // 'www.example.com'
console.log(myUrl.pathname); // '/path'
console.log(myUrl.searchParams.get('name')); // 'foo'
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . .