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')package main
import (
"fmt"
"os"
)
func main() {
// tạo file (và ghi vào đó)
if err := os.WriteFile("test.txt", []byte("hello world."), 0644); err != nil {
panic(err)
}
// đọc file
contents, err := os.ReadFile("test.txt")
if err != nil {
panic(err)
}
fmt.Println(string(contents))
// xoá file
if err := os.Remove("test.txt"); err != nil {
panic(err)
}
}use std::fs;
fn main() -> std::io::Result<()> {
// tạo file (và ghi vào đó)
fs::write("test.txt", "hello world.")?;
// đọc file
let contents = fs::read_to_string("test.txt")?;
println!("{contents}");
// xoá file
fs::remove_file("test.txt")?;
Ok(())
}import Foundation
// tạo file (và ghi vào đó)
try "hello world.".write(toFile: "test.txt", atomically: true, encoding: .utf8)
// đọc file
let contents = try String(contentsOfFile: "test.txt", encoding: .utf8)
print(contents)
// xoá file
try FileManager.default.removeItem(atPath: "test.txt")void main() throws Exception {
Path path = Path.of("test.txt");
// tạo file (và ghi vào đó)
Files.writeString(path, "hello world.");
// đọc file
String contents = Files.readString(path);
IO.println(contents);
// xoá file
Files.delete(path);
}hello world.Tham khảo: github.com/miguelmota/golang-for-nodejs-developers#files