2024-10-02|閱讀時間 ‧ 約 5 分鐘

Node.js 程式札記:核心模組 - 文件操作、網路請求與路徑處理

Node.js 是一個功能強大的 JavaScript 執行環境,它內建的核心模組讓開發者能夠輕鬆處理檔案系統操作、網路請求和路徑管理等常見需求。本文將介紹三個常用的 Node.js 核心模組,並透過範例程式碼展示它們的基本用法,幫助你快速上手。

文件系統操作(fs模組)

fs 模組是 Node.js 中用於檔案系統操作的核心模組,提供了讀取、寫入、修改檔案等功能。

讀取檔案

使用fs.readFile()方法可以非同步讀取檔案內容:

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('讀取檔案時發生錯誤:', err);
return;
}
console.log('檔案內容:', data);
});

寫入檔案

使用fs.writeFile()方法可以將資料寫入檔案:

const fs = require('fs');

const content = '這是要寫入檔案的內容';

fs.writeFile('output.txt', content, (err) => {
if (err) {
console.error('寫入檔案時發生錯誤:', err);
return;
}
console.log('檔案寫入成功');
});

網路操作(http / https 模組)

http 和 https 模組允許 Node.js 創建伺服器和發送 HTTP 請求。

創建簡單的 HTTP 伺服器

使用http模組創建一個基本的Web伺服器:

const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
});

server.listen(3000, () => {
console.log('伺服器運行在 http://localhost:3000/');
});

發送 HTTP 請求

使用 http 模組發送 GET 請求:

const http = require('http');

http.get('http://api.example.com/data', (res) => {
let data = '';

res.on('data', (chunk) => {
data += chunk;
});

res.on('end', () => {
console.log(JSON.parse(data));
});
}).on('error', (err) => {
console.error('請求發生錯誤:', err.message);
});

路徑處理(path模組)

path模組提供了處理檔案和目錄路徑的實用工具。

連接路徑

使用path.join()方法可以智能地連接路徑片段:

const path = require('path');

const fullPath = path.join('/home', 'user', 'documents', 'file.txt');
console.log(fullPath); // 輸出: /home/user/documents/file.txt

解析路徑

path.parse()方法可以解析路徑字串:

const path = require('path');

const pathInfo = path.parse('/home/user/documents/file.txt');
console.log(pathInfo);
// 輸出:
// {
// root: '/',
// dir: '/home/user/documents',
// base: 'file.txt',
// ext: '.txt',
// name: 'file'
// }

總結

本文介紹了 Node.js 的 fshttppath 三個核心模組,這些模組涵蓋了檔案讀寫、HTTP 伺服器建立和路徑處理等常見開發場景。掌握這些模組的基本用法,能讓你更有效率地處理後端開發中的各種需求。

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.