Rumah >hujung hadapan web >tutorial js >ost Modul Teras Terpakai Node.js

ost Modul Teras Terpakai Node.js

Mary-Kate Olsen
Mary-Kate Olsenasal
2024-11-15 14:11:02759semak imbas

ost Used Core Modules of Node.js
Node.js 模块本质上是一组可以包含在应用程序中的 JavaScript 函数或对象。节点模块使您能够将代码分解为更小的、可重用的部分。

核心模块:

它们内置于 Node.js 中并提供基本功能,例如 fs(文件系统)、http(HTTP 服务器/客户端)、路径、url 等。您可以使用 require()

来访问这些模块,而无需安装它们

这是开发人员在其项目中最常用的核心模块。

1. 路径

Node.js 中的路径模块提供了用于处理文件和目录路径的实用程序。以下是路径模块中最常用的一些方法。

路径.join()

将多个路径段组合成单个路径。它规范化结果路径,处理冗余斜杠或相对路径

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

路径.resolve()

从当前工作目录开始,将一系列路径或路径段解析为绝对路径。

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

路径.basename()

返回路径的最后一部分,通常是文件名。您还可以指定要从结果中删除的扩展名。

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

路径.目录名()

返回路径的目录部分。

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

路径.扩展名()

返回路径中文件的扩展名,包括点(.)。

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

路径.parse()

返回一个对象,其属性代表路径的不同部分

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

路径.isAbsolute()

检查路径是否是绝对路径,这意味着它从根目录开始(UNIX 上的 / 或 Windows 上的 C:)。

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

还有更多方法可以查看path模块的官方文档

2.fs(文件系统)

Node.js 中的 fs(文件系统)模块允许您与文件系统交互以读取、写入和操作文件和目录。下面是fs模块中最常用的一些方法

fs.readFile() 和 fs.readFileSync()

异步和同步读取文件内容。

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

fs.writeFile() 和 fs.writeFileSync()

异步和同步将数据写入文件。

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

fs.appendFile() & fs.appendFile()

以异步和同步方式将数据附加到文件。

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

fs.rename() 和 fs.renameSync()

异步和同步重命名或移动文件。

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

fs.unlink() 和 fs.unlinkSync()

异步和同步删除文件。

fs.unlink('example.txt', (err) => {
  if (err) throw err;
  console.log('File deleted');
});

fs.unlinkSync('example.txt');
console.log('File deleted');

fs.mkdir() & fs.mkdirSync()

Creates a new directory asynchronously and synchronously.

fs.mkdir('newDirectory', (err) => {
  if (err) throw err;
  console.log('Directory created');
});

fs.mkdirSync('newDirectory');
console.log('Directory created');

fs.existsSync()

Checks if a file or directory exists synchronously.

const exists = fs.existsSync('example.txt');
console.log(exists ? 'File exists' : 'File does not exist');

fs.copyFile()

Copies a file asynchronously from one location to another.

fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('File copied successfully');
});

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 EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

emitter.emit('greet', 'Alice'); // Output: Hello, Alice!

emitter.once()

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

emitter.once('welcome', (name) => {
  console.log(`Welcome, ${name}!`);
});

emitter.emit('welcome', 'Alice'); // Output: Welcome, Alice!
emitter.emit('welcome', 'Bob');   // No output (listener is removed after first call)

emitter.removeAllListeners()

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

emitter.on('goodbye', () => console.log('Goodbye!'));
emitter.removeAllListeners('goodbye');

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.

const { URL } = require('url');
const myUrl = new URL('https://example.com/path?name=John&age=30');

console.log(myUrl.searchParams.get('name'));  // Output: John

URL.toString() & URL.toJSON()

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

const { URL } = require('url');
const myUrl = new URL('https://example.com/path?name=John');
console.log(myUrl.toString()); 
// Output: https://example.com/path?name=John

console.log(myUrl.toJSON()); 
// Output: "https://example.com/path?name=John"

URL.hostname & URL.port

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

const { URL } = require('url');
const myUrl = new URL('https://example.com:8000/path?name=John');
console.log(myUrl.hostname); 
// Output: example.com

console.log(myUrl.port); 
// Output: 8000

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 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 is running on http://localhost:3000');
});

server.close(() => {
  console.log('Server has been closed');
});

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

Atas ialah kandungan terperinci ost Modul Teras Terpakai Node.js. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn