jsrosetta

I/O

Chạy tiến trình con (exec)

child_process.execSync/exec của Node.js so với os/exec (Go), std::process::Command (Rust), Process (Swift) và ProcessBuilder (Java).

Phiên bản tối thiểu
Node.js ≥ 14.13.1Go ≥ 1.7Rust ≥ 1.71Swift ≥ 5.7Java ≥ 25
Đã chạy thử trên
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Code Node.js là ES module: lưu file .mjs hoặc đặt "type": "module" trong package.json.

Chạy một lệnh hệ thống có hai kiểu: đợi nó chạy xong rồi mới tiếp tục (sync), hoặc chạy mà không chặn rồi xử lý kết quả sau (async). Go không có sự phân biệt đó: cmd.Run() luôn chặn (block) goroutine gọi nó. Rust std cũng vậy — Command::output() chặn thread hiện tại; muốn "async" thật sự phải dùng tokio::process::Command (không có trong std). Swift's Process cũng chỉ có API đồng bộ (waitUntilExit()); "async có timeout" phải tự ghép bằng Task. Java có sẵn cả hai: Process.waitFor() (block) và Process.onExit() trả về CompletableFuture<Process>.

Chạy đồng bộ (sync)

import { execSync } from 'node:child_process'
 
const output = execSync(`echo 'hello world'`)
 
console.log(output.toString())
hello world

Chạy bất đồng bộ (async) có timeout

import { exec } from 'node:child_process'
import { promisify } from 'node:util'
 
const execAsync = promisify(exec)
 
const { stdout, stderr } = await execAsync(`echo 'hello world'`, { timeout: 5000 })
 
if (stderr) {
  console.error(stderr)
}
 
console.log(stdout)
hello world

Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#exec-sync