Đọc đầu vào
Thuộc phần Kiến thức cơ bản về Node.js trong hành trình Node.js của Coddy. Bài học 30 trên 33.
Thêm ghi chú bằng từng lệnh một sẽ chậm nếu danh sách đã có sẵn ở nơi khác.
Chương trình cũng có thể đọc đầu vào từ stdin: văn bản được nhập bằng bàn phím hoặc gửi từ một tệp. Trên máy tính xách tay, cat numbers.txt | node sum.js gửi một tệp vào stdin; | được gọi là pipe. for await (const chunk of process.stdin) đọc từng phần cho đến khi hết. Ghép các phần lại, rồi tách chúng thành từng dòng.
// cat numbers.txt | node sum.js
let input = '';
for await (const chunk of process.stdin) {
input += chunk;
}
const numbers = input.split('\n').filter((line) => line !== '').map(Number);
console.log(numbers.reduce((a, b) => a + b, 0));Ở đây, ô Input của terminal điền dữ liệu vào stdin. Văn bản thường kết thúc bằng một ký tự xuống dòng, nên dòng cuối cùng sẽ trống: hãy bỏ các dòng trống.
Thử thách
DễNhập từng ghi chú một bằng add sẽ chậm nếu bạn đã có sẵn một danh sách ở đâu đó. Thêm lệnh import để đọc nhiều ghi chú cùng lúc từ đầu vào của chương trình, stdin.
- Trong
notes.js, thêm lệnhimport. Đọc toàn bộ stdin vào một chuỗi bằngfor await, như bài học hướng dẫn. - Tách văn bản thành các dòng. Xóa khoảng trắng ở đầu và cuối mỗi dòng, rồi bỏ qua những dòng trống sau khi xóa khoảng trắng.
- Thêm từng dòng còn lại làm ghi chú bằng
store.add, chờ từng lần gọi hoàn tất. Listeneraddedvẫn in ra một dòngSaved notecho mỗi ghi chú. Đây là kết quả mong đợi. - Cuối cùng, in ra
Imported, số ghi chú đã thêm vànotes.. Với đầu vào sau:Buy bread Call the bank Water the plantsnode notes.js importlưu ba dòng thành ghi chú. Lệnh này in ra ba dòngSaved note, rồi cuối cùng:Nếu không có đầu vào, lệnh chỉ in ra:Imported 3 notes.Imported 0 notes.
Thử nhé: nhấp vào nút Đầu vào bên cạnh nút Chạy. Một hộp sẽ mở ra bên dưới phần đối số. Nhập ba dòng vào đó, với một dòng trống ở giữa hai dòng. Nhập import vào hộp sau $ node notes.js rồi nhấn Enter. Sau đó xóa nội dung hộp Đầu vào và chạy lại import: bạn sẽ thấy Imported 0 notes..
Tự làm thử
// Công cụ ghi chú của bạn bắt đầu từ đây.
import { rmSync } from 'node:fs';
import path from 'node:path';
import { formatNote } from './format.js';
import stats from './legacy/stats.cjs';
import store from './store.js';
const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');
store.on('added', (note, n) => {
console.log(`Saved note ${n}.`);
});
const noteNumber = (word) => {
const n = Number(word);
if (!Number.isInteger(n) || n < 1 || n > store.notes.length) {
console.error(`No note ${word}`);
process.exit(1);
}
return n;
};
if (command === 'add') {
await store.add(text);
} else if (command === 'list') {
const owner = process.env.NOTES_OWNER ?? 'you';
console.log(`Notes for ${owner}`);
if (store.notes.length === 0) {
console.log('No notes yet');
}
const lines = store.notes.map((note, i) => formatNote(i + 1, note));
if (store.settings.sort === 'newest') {
lines.reverse();
}
lines.forEach((line) => console.log(line));
} else if (command === 'where') {
const file = path.join(process.cwd(), 'notes.json');
console.log(file);
console.log(path.basename(file));
} else if (command === 'stats') {
console.log(`${store.notes.length} notes, ${stats.countWords(store.notes)} words`);
} else if (command === 'done') {
const removed = await store.remove(noteNumber(words[0]));
console.log(`Done: ${removed}`);
} else if (command === 'remind') {
const note = store.notes[noteNumber(words[0]) - 1];
let count = 3;
const timer = setInterval(() => {
if (count > 0) {
console.log(count);
count -= 1;
} else {
console.log(note);
clearInterval(timer);
}
}, 200);
} else if (command === 'clear') {
rmSync('notes.json', { force: true });
console.log('Deleted notes.json');
} else {
if (command) {
console.error(`Unknown command: ${command}`);
}
console.error('Usage: node notes.js <command> [words]');
process.exit(1);
}
Tất cả bài học trong Kiến thức cơ bản về Node.js
Tự luyện tập: Playground Express