Back to JavaScript
2025-12-256 min read

Core modules (JavaScript)

Learn Core modules (JavaScript) step by step with clear examples and exercises.

Why This Matters

JavaScript Core Modules are an essential part of Node.js development, providing built-in functions and utilities that simplify various tasks, making it easier to build efficient, scalable, and secure applications. They offer capabilities for managing filesystem operations, network requests, cryptography, and more, which are crucial for projects requiring real-time data processing, server-side scripting, automation, and other advanced functionalities.

Prerequisites

Before diving into JavaScript Core Modules, you should have a good understanding of:

  1. Basic JavaScript syntax and concepts, such as variables, functions, loops, control structures, and ES6 features like arrow functions, template literals, and destructuring assignments.
  2. Node.js installation and basic command line navigation.
  3. Familiarity with the terminal or command prompt in your operating system.
  4. Understanding of asynchronous programming concepts, as many core modules are asynchronous by nature.
  5. Knowledge of file system navigation (e.g., directories, paths) to work effectively with filesystem modules.
  6. Familiarity with HTTP and network protocols for networking modules.
  7. Basic understanding of cryptography principles for working with cryptography modules.

Core Concept

JavaScript Core Modules can be divided into several categories:

  1. File System Modules: These include fs, path, and glob. They help with reading, writing, and managing files on the server. For example, using the fs module, you can read a file's content like this:
const fs = require('fs');
fs.readFile('filename.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
  1. Networking Modules: Examples are http, https, net, and dgram. They enable creating servers, handling requests, and communicating over networks. For example, you can create a simple HTTP server using the http module:
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

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

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
  1. Stream Modules: Streams allow for efficient handling of large amounts of data. Modules like stream, zlib, and crypto can be used for decompressing files, encryption, and more.
  1. Cryptography Modules: These include crypto and tls. They provide functions for hashing, decryption, and creating secure connections. For example, you can create a simple hash using the crypto module:
const crypto = require('crypto');
const sha256 = crypto.createHash('sha256');
sha256.update('Hello World');
console.log(sha256.digest('hex')); // Outputs the hash of 'Hello World' in hexadecimal format
  1. Util Modules: Examples are util, events, and assert. They offer utility functions like event handling, assertion checking, and more.
  1. Buffer API: The Buffer API allows you to handle raw data in a way that's compatible with both JavaScript strings and native Node.js APIs.

Worked Example

Let's create a simple server using the http module and read a file using the fs module:

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
fs.readFile('filename.txt', 'utf8', (err, data) => {
if (err) throw err;
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(data); // Send the file content as response
});
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

This script creates an HTTP server that reads a file named filename.txt and sends its content as the response for each request. Save the code in a file named server.js, then run it using Node.js:

node server.js

Now, if you navigate to http://127.0.0.1:3000/ in your browser, you should see the content of filename.txt displayed.

Common Mistakes

  1. Forgetting to require modules: Always remember to import the required modules at the beginning of your script using const or require.
  2. Not handling errors properly: Make sure to use try-catch blocks and error event listeners to handle potential issues gracefully.
  3. Misusing callbacks: Avoid nesting callbacks excessively; instead, consider using Promises or async/await for better readability and maintainability.
  4. Ignoring asynchronous nature of core modules: Be aware that many core modules are asynchronous, so you may need to use callbacks, Promises, or async/await to handle their results correctly.
  5. Not properly encoding data: When working with streams or file system operations, make sure to properly encode and decode data using the appropriate functions (e.g., Buffer.toString()).
  6. ### Using deprecated modules: Stay updated on the latest Node.js releases and avoid using deprecated modules whenever possible.
  7. ### Incorrectly handling streams: Be mindful of stream events like data, end, and error when working with streams to ensure proper handling of data and errors.
  8. Not closing streams: Remember to close streams after use, especially when dealing with resources that are limited (e.g., file handles).
  9. Not properly using event emitters: When working with event-based modules like events, make sure to correctly attach listeners and handle events appropriately.
  10. Not understanding the event loop: Be aware of how Node.js handles asynchronous tasks, as it can impact the performance and behavior of your code.

Practice Questions

  1. Write a script that reads a file named data.txt, processes its contents, and writes the result to another file named output.txt.
  2. Create an HTTP server that listens on port 3001 and responds with the current date and time for each request.
  3. Implement a simple chat server using the net module that allows two clients to communicate with each other.
  4. Write a script that compresses a file using the zlib module and saves it as a .gz file.
  5. Create an HTTPS server using the https module and implement basic authentication for accessing certain routes.
  6. Write a script that generates an RSA public/private key pair using the crypto module, encrypts a message with the public key, and decrypts it using the private key.
  7. Implement a simple web scraper using the http, fs, and cheerio modules to extract data from a website and save it to a file.
  8. Create an API server using the express module that allows users to upload files and returns their hashes generated by the crypto module.
  9. Write a script that uses the dns module to resolve hostnames to IP addresses and stores the results in a file.
  10. Implement a simple email sender using the nodemailer module that sends an email with a custom message and attachment.

FAQ

  1. Why are core modules important for web development? Core modules simplify common tasks, making it easier to build efficient and scalable applications. They also provide a consistent API across different projects.
  2. How do I find out which JavaScript core modules exist? You can explore the available core modules by visiting the Node.js API documentation or using tools like npm docs.
  3. Can I use JavaScript core modules in a browser environment? While most core modules are designed for Node.js server-side development, some can be used in the browser with tools like Web Workers.
  4. What is the difference between require and const when importing core modules? Both can be used to import core modules, but const provides a more concise syntax and helps prevent accidental reassignment of imported modules.
  5. Why are some JavaScript core modules asynchronous by nature? Many core modules deal with I/O operations like reading files or making network requests, which are inherently asynchronous due to their non-deterministic nature. Asynchronous programming allows the Node.js runtime to handle these operations efficiently without blocking the event loop.
  6. How can I optimize my code when using core modules? To optimize your code, consider using asynchronous functions instead of synchronous ones, minimizing the use of nested callbacks, and properly handling errors for better performance and error handling.
  7. What are some best practices for working with streams in Node.js? When working with streams, it's essential to handle events like data, end, and error appropriately, pipe streams together when possible, and close the stream once you're done processing its data.
Core modules (JavaScript) | JavaScript | XQA Learn