Types of API functions in Node.js

Last Updated : 15 Sep, 2025

Node.js is a powerful platform for building scalable applications, leveraging its asynchronous, event-driven architecture. It provides a variety of API functions that facilitate interactions with the system, enabling developers to handle tasks like communication, file management, and data processing efficiently.

1. Core Module API Functions

Node.js includes several built-in modules that provide essential functionalities through their API functions. These modules are integral to the Node.js ecosystem and support a wide range of operations.

HTTP/HTTPS API Functions

These functions enable the creation of web servers and the handling of HTTP/HTTPS requests. For example:

  • http.createServer(): Creates an HTTP server to handle incoming requests.
  • https.request(): Initiates secure HTTPS requests to external servers.

These functions are commonly used to build RESTful APIs or serve web content.

File System (fs) API Functions

The fs module provides functions for interacting with the file system, allowing operations like reading, writing, and deleting files or directories. Examples include:

  • fs.readFile(): Asynchronously reads the contents of a file.
  • fs.writeFile(): Writes data to a file, creating or overwriting it.
  • fs.mkdir(): Creates a new directory.

These functions are essential for file management tasks in Node.js applications.

Stream API Functions

Streams enable efficient handling of large data sets by processing them in chunks rather than loading them entirely into memory. Key functions include:

  • fs.createReadStream(): Reads data from a file as a stream.
  • fs.createWriteStream(): Writes data to a file as a stream.
  • zlib.createDeflate(): Compresses data using the deflate algorithm.

Streams are particularly useful for handling large files or real-time data transfers.

Path API Functions

The path module provides utilities for working with file and directory paths. Examples include:

  • path.join(): Concatenates path segments into a single path.
  • path.basename(): Extracts the file name from a path.

These functions ensure cross-platform compatibility when handling file paths.

Event Emitter API Functions

The events module supports event-driven programming, a core feature of Node.js. Key functions include:

  • eventEmitter.on(): Registers a listener for a specific event.
  • eventEmitter.emit(): Triggers an event, invoking all registered listeners.

These functions are foundational for building reactive, event-driven applications.

2. Asynchronous vs. Synchronous API Functions

Node.js API functions can be categorized based on their execution model: asynchronous (non-blocking) or synchronous (blocking).

Asynchronous, Non-blocking Functions

Asynchronous functions are designed for I/O-intensive operations, such as file reading or network requests, and do not block the main thread. They typically use callbacks, Promises, or async/await to handle results. For example:

  • fs.readFile(): Reads a file asynchronously, invoking a callback with the data.
  • http.get(): Makes an asynchronous HTTP GET request.

These functions allow Node.js to handle multiple operations concurrently, improving performance in high-load scenarios.

Synchronous, Blocking Functions

Synchronous functions block the main thread until the operation completes, making them suitable for quick tasks or scenarios where immediate results are required. Examples include:

  • fs.readFileSync(): Reads a file synchronously, returning the data directly.
  • fs.writeFileSync(): Writes data to a file synchronously.

While simpler to use, synchronous functions can degrade performance in I/O-heavy applications due to their blocking nature.

Example: Reading a JSON File

Consider a JSON file named data.json with the following content:

JSON
{
  "name": "John",
  "age": 50,
  "gender": "male"
}

The following code demonstrates both asynchronous and synchronous file reading using the fs module:

JavaScript
// index.js
const fs = require('fs');

// Asynchronous function
fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) {
    return console.log(err);
  }
  console.log("Data from Asynchronous function call:");
  console.log(data);
});

// Synchronous function
const data = fs.readFileSync('data.json', 'utf8');
console.log("Data from Synchronous function call:");
console.log(data);

Steps to Run:

  1. Save the code in a file named index.js.
  2. Ensure data.json exists in the same directory.
  3. Run the application using:
node index.js

Output:

Data from Synchronous function call:
{
"name": "John",
"age": 50,
"gender": "male"
}
Data from Asynchronous function call:
{
"name": "John",
"age": 50,
"gender": "male"
}

Key Observations:

  • The synchronous call outputs first because it blocks execution until complete.
  • For small files, the performance difference is minimal, but asynchronous methods excel in scenarios with multiple operations or high I/O demands.

3. Third-party Library API Functions

Node.js's ecosystem is enriched by third-party libraries and frameworks, which provide specialized API functions for various tasks.

Web Frameworks

Frameworks like Express.js, Koa, and Hapi simplify web application development with functions for routing, middleware, and request/response handling. Examples include:

  • app.get() (Express.js): Defines a route for HTTP GET requests.
  • res.send() (Express.js): Sends a response to the client.

These functions streamline the creation of RESTful APIs and web servers.

Database Drivers

Libraries like mongoose (for MongoDB) and pg (for PostgreSQL) provide API functions for database interactions. Examples include:

  • Model.find() (Mongoose): Retrieves documents from a MongoDB collection.
  • client.query() (pg): Executes a SQL query on a PostgreSQL database.

These functions abstract database operations, making it easier to manage data.

Authentication Libraries

Libraries like Passport.js provide API functions for user authentication and authorization. For example:

  • passport.authenticate(): Authenticates a user request using a specified strategy.

These functions simplify secure user management in applications.

4. N-API Functions (Native Addons)

N-API (Node-API) enables developers to create high-performance native add-ons in C/C++ that integrate seamlessly with Node.js. These functions provide a stable application binary interface (ABI) for:

  • Object Creation and Manipulation: Creating and modifying JavaScript objects from C/C++.
  • Error Handling: Managing exceptions and errors in native code.
  • JavaScript Value Handling: Working with JavaScript types like strings, numbers, and arrays.
  • Asynchronous Operations: Supporting asynchronous tasks and Promises in native add-ons.

N-API functions are ideal for performance-critical tasks that require low-level system access.

Comment

Explore