首頁 > web前端 > js教程 > ost 使用的 Node.js 核心模組

ost 使用的 Node.js 核心模組

Mary-Kate Olsen
發布: 2024-11-15 14:11:02
原創
763 人瀏覽過

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

以上是ost 使用的 Node.js 核心模組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板