Home > Web Front-end > JS Tutorial > ost Used Core Modules of Node.js

ost Used Core Modules of Node.js

Mary-Kate Olsen
Release: 2024-11-15 14:11:02
Original
772 people have browsed it

ost Used Core Modules of Node.js
A Node.js module is essentially a set of JavaScript functions or objects that can be included in an application. Node modules enable you to break up your code into smaller, reusable pieces.

Core Modules:

These are built into Node.js and provide essential functionality, such as fs (file system), http (HTTP server/client), path, url, and more. You can access these modules without installing them by using require()

Here is the most used core modules developer used in their project.

1. path

The path module in Node.js provides utilities for working with file and directory paths. Here are some of the most commonly used methods in the path module.

path.join()

Combines multiple path segments into a single path. It normalizes the resulting path, handling redundant slashes or relative paths

const path = require('path');
const filePath = path.join('/users', 'john', 'documents', 'file.txt');
console.log(filePath); 
// Output: /users/john/documents/file.txt
Copy after login
Copy after login
Copy after login

path.resolve()

Resolves a sequence of paths or path segments into an absolute path, starting from the current working directory.

const absolutePath = path.resolve('documents', 'file.txt');
console.log(absolutePath); 
// Output: /your/current/working/directory/documents/file.txt
Copy after login
Copy after login

path.basename()

Returns the last part of a path, usually the file name. You can also specify an extension to remove from the result.

const fullPath = '/users/john/file.txt';
console.log(path.basename(fullPath));       
 // Output: file.txt
console.log(path.basename(fullPath, '.txt')); 
// Output: file
Copy after login
Copy after login

path.dirname()

Returns the directory portion of a path.

const filePath = '/users/john/documents/file.txt';
console.log(path.dirname(filePath)); 
// Output: /users/john/documents
Copy after login
Copy after login

path.extname()

Returns the extension of the file in the path, including the dot (.).

const filePath = '/users/john/documents/file.txt';
console.log(path.dirname(filePath));
 // Output: /users/john/documents
Copy after login
Copy after login

path.parse()

Returns an object with properties representing different parts of the path

const parsedPath = path.parse('/users/john/file.txt');
console.log(parsedPath);
/* Output:
{
  root: '/',
  dir: '/users/john',
  base: 'file.txt',
  ext: '.txt',
  name: 'file'
}
*/
Copy after login
Copy after login

path.isAbsolute()

Checks if a path is absolute, meaning it starts from the root directory (/ on UNIX or C: on Windows).

console.log(path.isAbsolute('/users/john'));  
// Output: true
console.log(path.isAbsolute('file.txt'));    
 // Output: false
Copy after login
Copy after login

There are more methods you can use for that check official document of path module

2. fs (File System)

The fs (File System) module in Node.js allows you to interact with the file system to read, write, and manipulate files and directories. Here are some of the most commonly used methods in the fs module

fs.readFile() & fs.readFileSync()

Reads the contents of a file asynchronously and synchronously.

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

const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Copy after login
Copy after login

fs.writeFile() & fs.writeFileSync()

Writes data to a file asynchronously and synchronously.

fs.writeFile('example.txt', 'Hello, World!', (err) => {
  if (err) throw err;
  console.log('File written successfully');
});

fs.writeFileSync('example.txt', 'Hello, World!');
console.log('File written successfully');
Copy after login
Copy after login

fs.appendFile() & fs.appendFile()

Appends data to a file asynchronously and synchronously.

fs.appendFile('example.txt', 'Hello, World!', (err) => {
  if (err) throw err;
  console.log('File written successfully');
});

fs.appendFileSync('example.txt', 'Hello, World!');
console.log('File written successfully');
Copy after login
Copy after login

fs.rename() & fs.renameSync()

Renames or moves a file asynchronously and synchronously.

const path = require('path');
const filePath = path.join('/users', 'john', 'documents', 'file.txt');
console.log(filePath); 
// Output: /users/john/documents/file.txt
Copy after login
Copy after login
Copy after login

fs.unlink() & fs.unlinkSync()

Deletes a file asynchronously and synchronously.

const absolutePath = path.resolve('documents', 'file.txt');
console.log(absolutePath); 
// Output: /your/current/working/directory/documents/file.txt
Copy after login
Copy after login

fs.mkdir() & fs.mkdirSync()

Creates a new directory asynchronously and synchronously.

const fullPath = '/users/john/file.txt';
console.log(path.basename(fullPath));       
 // Output: file.txt
console.log(path.basename(fullPath, '.txt')); 
// Output: file
Copy after login
Copy after login

fs.existsSync()

Checks if a file or directory exists synchronously.

const filePath = '/users/john/documents/file.txt';
console.log(path.dirname(filePath)); 
// Output: /users/john/documents
Copy after login
Copy after login

fs.copyFile()

Copies a file asynchronously from one location to another.

const filePath = '/users/john/documents/file.txt';
console.log(path.dirname(filePath));
 // Output: /users/john/documents
Copy after login
Copy after login

There are more methods you can use for that check official document of fs module

3. events

The events module in Node.js is essential for implementing event-driven programming. It allows you to create, listen to, and manage custom events. The most commonly used class in this module is EventEmitter, which provides various methods for handling events. Here are some of the most used methods:

emitter.on()

Registers a listener (callback function) for a specific event. Multiple listeners can be registered for a single event.

emitter.emit()

Emits a specific event, triggering all listeners registered for that event. You can pass arguments to the listeners.

const parsedPath = path.parse('/users/john/file.txt');
console.log(parsedPath);
/* Output:
{
  root: '/',
  dir: '/users/john',
  base: 'file.txt',
  ext: '.txt',
  name: 'file'
}
*/
Copy after login
Copy after login

emitter.once()

Registers a listener for an event that will be called only once. After the event is emitted, the listener is automatically removed.

console.log(path.isAbsolute('/users/john'));  
// Output: true
console.log(path.isAbsolute('file.txt'));    
 // Output: false
Copy after login
Copy after login

emitter.removeAllListeners()

Removes all listeners for a specific event or for all events if no event is specified.

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

const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Copy after login
Copy after login

There are more methods you can use for that check official document of events module

4. URL()

The url module in Node.js provides utilities for URL parsing, formatting, and resolving. This module is useful for handling and manipulating URL strings in web applications.

new URL()

Creates a new URL object, which parses a given URL and provides access to its components.

URL.searchParams

Creates a new URL object, which parses a given URL and provides access to its components.

fs.writeFile('example.txt', 'Hello, World!', (err) => {
  if (err) throw err;
  console.log('File written successfully');
});

fs.writeFileSync('example.txt', 'Hello, World!');
console.log('File written successfully');
Copy after login
Copy after login

URL.toString() & URL.toJSON()

Converts a URL object into a string representation. Serializes the URL as a JSON string

fs.appendFile('example.txt', 'Hello, World!', (err) => {
  if (err) throw err;
  console.log('File written successfully');
});

fs.appendFileSync('example.txt', 'Hello, World!');
console.log('File written successfully');
Copy after login
Copy after login

URL.hostname & URL.port

Gets or sets the hostname portion of the URL (without port). Gets or sets the port portion of the URL.

fs.rename('example.txt', 'renamed.txt', (err) => {
  if (err) throw err;
  console.log('File renamed successfully');
});

fs.renameSync('example.txt', 'renamed.txt');
console.log('File renamed successfully');
Copy after login

There are more methods you can use for that check official document of url module

5. http

The http module in Node.js provides functionality to create and handle HTTP requests and responses. Here are some of the most commonly used methods in the http module:

http.createServer()

Creates an HTTP server that listens for incoming requests. This method returns an instance of http.Server.

server.listen()

Starts the HTTP server and listens for requests on the specified port and host.

server.close()

Stops the server from accepting new connections and closes existing connections.

const path = require('path');
const filePath = path.join('/users', 'john', 'documents', 'file.txt');
console.log(filePath); 
// Output: /users/john/documents/file.txt
Copy after login
Copy after login
Copy after login

There are more methods you can use for that check official document of http module

The above is the detailed content of ost Used Core Modules of Node.js. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template