NPM - Using Built-in Modules

NPM - Using Built-in Modules

Using Built-in Modules - NPM 

Node.js provides a rich library of built-in modules that can be used without any additional installation. These modules form the core functionality of Node.js and are designed to perform a wide variety of essential tasks such as file system operations, networking, cryptography, buffer handling, stream management, and much more. Understanding how to use these built-in modules is vital for any developer working with Node.js and NPM (Node Package Manager).

Introduction to Built-in Modules

Built-in modules are also known as core modules. They are compiled into the Node.js binary and are part of the Node.js runtime environment. As such, they can be used in any Node.js application without being explicitly installed via NPM.

To use a built-in module, you simply require it using the `require()` function. These modules provide functionality that covers a broad range of server-side use cases.

Example Syntax

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

In the above example, we are using the built-in `fs` (File System) and `http` (HTTP server) modules.

List of Commonly Used Built-in Modules

Here is a list of some of the most commonly used built-in modules in Node.js:

  • fs – File System
  • http – HTTP Server and Client
  • https – HTTPS Server and Client
  • path – Path Utilities
  • os – Operating System Info
  • url – URL Parsing
  • events – Event Emitter
  • stream – Streaming Data
  • crypto – Cryptographic Functions
  • util – Utilities
  • querystring – Query String Parser
  • zlib – Compression

Working with the fs Module

The `fs` module allows you to work with the file system. You can read, write, delete, and perform many other file-related operations.

Reading a File

const fs = require('fs');

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

Writing to a File

fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log('File written successfully!');
});

Using the http Module

The `http` module allows you to create web servers and handle HTTP requests and responses.

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

server.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Working with the path Module

The `path` module provides utilities for working with file and directory paths. It is especially useful when building file paths that work across different operating systems.

Joining Paths

const path = require('path');

const fullPath = path.join(__dirname, 'folder', 'file.txt');
console.log(fullPath);

Getting File Extension

const ext = path.extname('index.html');
console.log(ext); // .html

Using the os Module

The `os` module provides operating system-related utility methods and properties.

Getting System Information

const os = require('os');

console.log('Platform:', os.platform());
console.log('CPU Architecture:', os.arch());
console.log('Total Memory:', os.totalmem());
console.log('Free Memory:', os.freemem());

Working with the url Module

The `url` module is used for URL resolution and parsing.

Parsing a URL

const url = require('url');

const parsedUrl = url.parse('https://example.com/path?name=John');
console.log(parsedUrl.hostname); // example.com
console.log(parsedUrl.query); // name=John

Using the events Module

The `events` module allows you to handle custom events and is the foundation of the event-driven architecture in Node.js.

Creating and Handling Events

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

emitter.on('greet', () => {
  console.log('Hello from event!');
});

emitter.emit('greet');

Working with the stream Module

The `stream` module provides APIs for working with streaming data. There are four types of streams: readable, writable, duplex, and transform.

Reading a File Stream

const fs = require('fs');

const readStream = fs.createReadStream('example.txt', 'utf8');
readStream.on('data', (chunk) => {
  console.log(chunk);
});

Using the crypto Module

The `crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.

Creating a Hash

const crypto = require('crypto');

const hash = crypto.createHash('sha256').update('Hello').digest('hex');
console.log(hash);

Working with the util Module

The `util` module provides various utility functions. It is often used for debugging and inheritance.

Using util.format()

const util = require('util');

console.log(util.format('%s:%s', 'foo', 'bar'));

Using the querystring Module

The `querystring` module provides utilities for parsing and formatting URL query strings.

Parsing Query Strings

const querystring = require('querystring');

const parsed = querystring.parse('name=John&age=25');
console.log(parsed.name); // John

Using the zlib Module

The `zlib` module provides compression functionality using the Gzip and Deflate algorithms.

Compressing a File

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

const gzip = zlib.createGzip();
const input = fs.createReadStream('example.txt');
const output = fs.createWriteStream('example.txt.gz');

input.pipe(gzip).pipe(output);

Best Practices for Using Built-in Modules

  • Always handle errors when using asynchronous APIs.
  • Prefer built-in modules over third-party ones when possible.
  • Use path utilities to handle file paths to ensure cross-platform compatibility.
  • Take advantage of the streaming API for handling large data.
  • Use the `events` module to build modular, scalable applications.

Combining Multiple Modules

Often, you will use multiple modules together to build a feature-rich application. Here's an example that combines `http`, `fs`, and `path` to serve static files.

Simple Static File Server

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

const server = http.createServer((req, res) => {
  let filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url);
  const ext = path.extname(filePath);
  let contentType = 'text/html';

  if (ext === '.js') contentType = 'text/javascript';
  else if (ext === '.css') contentType = 'text/css';

  fs.readFile(filePath, (err, content) => {
    if (err) {
      res.writeHead(500);
      res.end('Server Error');
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});

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

Node.js built-in modules are powerful tools that allow developers to build robust and efficient applications without the need to install third-party packages. They offer foundational capabilities such as file handling, server creation, data compression, and cryptography. By mastering these core modules, developers can not only write cleaner code but also reduce external dependencies, leading to more secure and performant applications. Understanding how to use and combine built-in modules is a critical step in becoming an effective Node.js developer.

Beginner 5 Hours
NPM - Using Built-in Modules

Using Built-in Modules - NPM 

Node.js provides a rich library of built-in modules that can be used without any additional installation. These modules form the core functionality of Node.js and are designed to perform a wide variety of essential tasks such as file system operations, networking, cryptography, buffer handling, stream management, and much more. Understanding how to use these built-in modules is vital for any developer working with Node.js and NPM (Node Package Manager).

Introduction to Built-in Modules

Built-in modules are also known as core modules. They are compiled into the Node.js binary and are part of the Node.js runtime environment. As such, they can be used in any Node.js application without being explicitly installed via NPM.

To use a built-in module, you simply require it using the `require()` function. These modules provide functionality that covers a broad range of server-side use cases.

Example Syntax

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

In the above example, we are using the built-in `fs` (File System) and `http` (HTTP server) modules.

List of Commonly Used Built-in Modules

Here is a list of some of the most commonly used built-in modules in Node.js:

  • fs – File System
  • http – HTTP Server and Client
  • https – HTTPS Server and Client
  • path – Path Utilities
  • os – Operating System Info
  • url – URL Parsing
  • events – Event Emitter
  • stream – Streaming Data
  • crypto – Cryptographic Functions
  • util – Utilities
  • querystring – Query String Parser
  • zlib – Compression

Working with the fs Module

The `fs` module allows you to work with the file system. You can read, write, delete, and perform many other file-related operations.

Reading a File

const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log(data); });

Writing to a File

fs.writeFile('output.txt', 'Hello, Node.js!', (err) => { if (err) { console.error(err); return; } console.log('File written successfully!'); });

Using the http Module

The `http` module allows you to create web servers and handle HTTP requests and responses.

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!'); }); server.listen(3000, () => { console.log('Server is running on port 3000'); });

Working with the path Module

The `path` module provides utilities for working with file and directory paths. It is especially useful when building file paths that work across different operating systems.

Joining Paths

const path = require('path'); const fullPath = path.join(__dirname, 'folder', 'file.txt'); console.log(fullPath);

Getting File Extension

const ext = path.extname('index.html'); console.log(ext); // .html

Using the os Module

The `os` module provides operating system-related utility methods and properties.

Getting System Information

const os = require('os'); console.log('Platform:', os.platform()); console.log('CPU Architecture:', os.arch()); console.log('Total Memory:', os.totalmem()); console.log('Free Memory:', os.freemem());

Working with the url Module

The `url` module is used for URL resolution and parsing.

Parsing a URL

const url = require('url'); const parsedUrl = url.parse('https://example.com/path?name=John'); console.log(parsedUrl.hostname); // example.com console.log(parsedUrl.query); // name=John

Using the events Module

The `events` module allows you to handle custom events and is the foundation of the event-driven architecture in Node.js.

Creating and Handling Events

const EventEmitter = require('events'); const emitter = new EventEmitter(); emitter.on('greet', () => { console.log('Hello from event!'); }); emitter.emit('greet');

Working with the stream Module

The `stream` module provides APIs for working with streaming data. There are four types of streams: readable, writable, duplex, and transform.

Reading a File Stream

const fs = require('fs'); const readStream = fs.createReadStream('example.txt', 'utf8'); readStream.on('data', (chunk) => { console.log(chunk); });

Using the crypto Module

The `crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.

Creating a Hash

const crypto = require('crypto'); const hash = crypto.createHash('sha256').update('Hello').digest('hex'); console.log(hash);

Working with the util Module

The `util` module provides various utility functions. It is often used for debugging and inheritance.

Using util.format()

const util = require('util'); console.log(util.format('%s:%s', 'foo', 'bar'));

Using the querystring Module

The `querystring` module provides utilities for parsing and formatting URL query strings.

Parsing Query Strings

const querystring = require('querystring'); const parsed = querystring.parse('name=John&age=25'); console.log(parsed.name); // John

Using the zlib Module

The `zlib` module provides compression functionality using the Gzip and Deflate algorithms.

Compressing a File

const zlib = require('zlib'); const fs = require('fs'); const gzip = zlib.createGzip(); const input = fs.createReadStream('example.txt'); const output = fs.createWriteStream('example.txt.gz'); input.pipe(gzip).pipe(output);

Best Practices for Using Built-in Modules

  • Always handle errors when using asynchronous APIs.
  • Prefer built-in modules over third-party ones when possible.
  • Use path utilities to handle file paths to ensure cross-platform compatibility.
  • Take advantage of the streaming API for handling large data.
  • Use the `events` module to build modular, scalable applications.

Combining Multiple Modules

Often, you will use multiple modules together to build a feature-rich application. Here's an example that combines `http`, `fs`, and `path` to serve static files.

Simple Static File Server

const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { let filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url); const ext = path.extname(filePath); let contentType = 'text/html'; if (ext === '.js') contentType = 'text/javascript'; else if (ext === '.css') contentType = 'text/css'; fs.readFile(filePath, (err, content) => { if (err) { res.writeHead(500); res.end('Server Error'); } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf-8'); } }); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });

Node.js built-in modules are powerful tools that allow developers to build robust and efficient applications without the need to install third-party packages. They offer foundational capabilities such as file handling, server creation, data compression, and cryptography. By mastering these core modules, developers can not only write cleaner code but also reduce external dependencies, leading to more secure and performant applications. Understanding how to use and combine built-in modules is a critical step in becoming an effective Node.js developer.

Related Tutorials

Frequently Asked Questions for Node.js

A function passed as an argument and executed later.

Runs multiple instances to utilize multi-core systems.

Reusable blocks of code, exported and imported using require() or import.

nextTick() executes before setImmediate() in the event loop.

Starts a server and listens on specified port.

Node Package Manager β€” installs, manages, and shares JavaScript packages.

A minimal and flexible web application framework for Node.js.

A stream handles reading or writing data continuously.

It processes asynchronous callbacks and non-blocking I/O operations efficiently.

Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.

An object representing the eventual completion or failure of an asynchronous operation.

require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).

Use module.exports or exports.functionName.

Variables stored outside the code for configuration, accessed using process.env.


MongoDB, often used with Mongoose for schema management.

Describes project details and manages dependencies and scripts.

Synchronous blocks execution; asynchronous runs in background without blocking.

Allows or restricts resources shared between different origins.

Use try-catch, error events, or middleware for error handling.

Provides file system-related operations like read, write, delete.

Using event-driven architecture and non-blocking I/O.

Functions in Express that execute during request-response cycle.

A set of routes or endpoints to interact with server logic or databases.

Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.

Middleware to parse incoming request bodies, like JSON or form data.

line

Copyrights © 2024 letsupdateskills All rights reserved