Menu
CoddyTech

Đọ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 từng ghi chú bằng một lệnh 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 gõ bằng bàn phím hoặc đượ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 trong terminal điền dữ liệu vào stdin. Văn bản thường kết thúc bằng ký tự xuống dòng, vì vậy dòng cuối cùng sẽ trống: hãy loại bỏ các dòng trống.

challenge icon

Thử thách

Dễ

Gõ từng ghi chú bằng lệnh add sẽ mất thời gian 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.

  1. Trong notes.js, thêm lệnh import. Đọc toàn bộ stdin vào một chuỗi bằng for await, như bài học hướng dẫn.
  2. 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.
  3. 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. Trình lắng nghe added của bạn vẫn in ra một dòng Saved note cho mỗi ghi chú. Đây là điều bình thường.
  4. 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 plants
    node notes.js import lưu ba dòng thành các ghi chú. Lệnh in ra ba dòng Saved note, rồi cuối cùng:
    Imported 3 notes.
    Nếu không có đầu vào, lệnh chỉ in ra:
    Imported 0 notes.

Thử ngay: nhấp vào nút Input bên cạnh Run. Một ô 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 ô sau $ node notes.js rồi nhấn Enter. Sau đó xóa nội dung ô Input 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