在Ubuntu環境下,使用JavaScript實現并發處理可以通過多種方式來完成。以下是一些常見的方法:
const fs = require('fs');
// 異步讀取文件
fs.readFile('/path/to/file', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 異步寫入文件
fs.writeFile('/path/to/file', 'Hello World!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});
const fs = require('fs').promises;
async function readFileAsync(filePath) {
try {
const data = await fs.readFile(filePath, 'utf8');
console.log(data);
} catch (error) {
console.error(error);
}
}
async function writeFileAsync(filePath, data) {
try {
await fs.writeFile(filePath, data);
console.log('File has been saved!');
} catch (error) {
console.error(error);
}
}
worker_threads
模塊允許你在單獨的線程中運行JavaScript代碼,這樣可以實現真正的并行計算。const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
// 主線程
const worker = new Worker(__filename);
worker.on('message', (message) => {
console.log('Message from worker:', message);
});
} else {
// 工作線程
parentPort.postMessage('Hello from worker!');
}
child_process
模塊可以讓你生成新的進程,執行外部命令或者啟動新的Node.js腳本。const { spawn } = require('child_process');
// 創建一個子進程
const child = spawn('ls', ['-lh', '/usr']);
// 監聽子進程的標準輸出
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
// 監聽子進程的標準錯誤
child.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
// 監聽子進程退出事件
child.on('close', (code) => {
console.log(`Child exited with code ${code}`);
});
async
庫提供了很多用于控制并發流程的工具函數。const async = require('async');
// 并發執行多個異步任務
async.parallel([
function(callback) {
setTimeout(() => {
callback(null, 'one');
}, 200);
},
function(callback) {
setTimeout(() => {
callback(null, 'two');
}, 100);
}
], (err, results) => {
// results now equals ['one','two'] if no errors occurred
});
選擇哪種方法取決于你的具體需求和應用場景。對于I/O密集型任務,Node.js的異步特性通常就足夠了;而對于CPU密集型任務,可能需要考慮使用Worker Threads或者Child Processes來實現真正的并行處理。