jsrosetta

I/O

Đọc, ghi và xoá file

readFile/writeFile của Node.js so với os.ReadFile/os.WriteFile (Go), std::fs (Rust), FileManager (Swift) và java.nio.file.Files (Java).

Phiên bản tối thiểu
Node.js ≥ 14.13.1Go ≥ 1.16Rust ≥ 1.58Swift ≥ 3.0Java ≥ 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.

Cả năm ngôn ngữ đều có API bậc cao để tạo, đọc và xoá file mà không cần quản lý file descriptor thủ công. Node.js dùng các hàm Promise-based trong node:fs/promises; Go trả về (giá trị, error) trực tiếp — không có exception, chỉ có err bạn phải kiểm tra ngay sau mỗi lời gọi; Rust cũng trả Result nhưng dùng ? để đẩy lỗi lên thay vì kiểm tra thủ công; Swift và Java dùng exception (throws/try) giống JavaScript, chỉ chặt hơn về kiểu lỗi.

Tạo, ghi, đọc và xoá file

import { readFile, unlink, writeFile } from 'node:fs/promises'
 
// tạo file (và ghi vào đó)
await writeFile('test.txt', 'hello world.')
 
// đọc file
const contents = await readFile('test.txt', 'utf8')
console.log(contents)
 
// xoá file
await unlink('test.txt')
hello world.

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