jsrosetta

I/O

Đọc từ Stdin

readline/promises của Node.js so với bufio.Reader (Go), io::stdin (Rust), readLine() (Swift) và IO.readln (Java) để đọc một dòng nhập.

Phiên bản tối thiểu
Node.js ≥ 17Go ≥ 1.0Rust ≥ 1.58Swift ≥ 2.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 input tương tác từ người dùng nghĩa là đợi một dòng text kết thúc bằng Enter. Node.js có module readline/promises để await câu trả lời, Go dùng bufio.Reader đọc tới ký tự xuống dòng, Rust đọc qua io::stdin().read_line(), Swift có sẵn hàm toàn cục readLine(), còn Java 25 có IO.readln(prompt) — in prompt và đọc một dòng chỉ trong một lời gọi.

Đọc một dòng từ stdin

import { createInterface } from 'node:readline/promises'
 
const rl = createInterface({ input: process.stdin, output: process.stdout })
 
const name = await rl.question('Enter name: ')
console.log('Your name is: ' + name)
 
rl.close()
Enter name: bob
Your name is: bob

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