Home  >  Article  >  Web Front-end  >  Common built-in APIs in Nodejs

Common built-in APIs in Nodejs

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 13:03:02640browse

Common built-in APIs in Nodejs

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);
});

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/');
});

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

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());

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

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);
});

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

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

const fs = require('fs');

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

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

Example: Generating a SHA-256 hash

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/');
});

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 path = require('path');

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

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

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());

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

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

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

emitter.emit('event'); // Triggers the event listener

The above is the detailed content of Common built-in APIs in Nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn