Menu
CoddyTech

Membaca Input

Termasuk bagian Dasar-Dasar Node.js dalam perjalanan Node.js di Coddy. Pelajaran 30 dari 33.

Menambahkan catatan satu perintah setiap kali terasa lambat jika daftarnya sudah tersedia di tempat lain.

Program juga dapat membaca input dari stdin: teks yang diketik di keyboard atau dikirim dari file. Di laptop, cat numbers.txt | node sum.js mengirim file ke stdin; | disebut pipa. for await (const chunk of process.stdin) membacanya bagian demi bagian sampai selesai. Gabungkan bagian-bagian itu, lalu pisahkan menjadi baris.

// 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));

Di sini, kotak Input di terminal mengisi stdin. Teks biasanya diakhiri dengan karakter baris baru, sehingga baris terakhir kosong: hapus baris yang kosong.

challenge icon

Tantangan

Mudah

Mengetik catatan satu per satu dengan add memakan waktu jika kamu sudah punya daftar di suatu tempat. Tambahkan perintah import yang membaca banyak catatan sekaligus dari input program, stdin.

  1. Di notes.js, tambahkan perintah import. Baca seluruh stdin ke dalam satu string dengan for await, seperti yang ditunjukkan pelajaran.
  2. Pisahkan teks menjadi beberapa baris. Pangkas spasi di awal dan akhir setiap baris, lalu lewati baris yang kosong setelah dipangkas.
  3. Tambahkan setiap baris yang tersisa sebagai catatan dengan store.add, tunggu setiap penambahannya. Listener added-mu tetap mencetak satu baris Saved note untuk setiap catatan. Itu memang diharapkan.
  4. Terakhir, cetak Imported , jumlah catatan yang ditambahkan, dan notes.. Dengan input ini:
    Buy bread
    Call the bank
    
    Water the plants
    node notes.js import menyimpan ketiga baris itu sebagai catatan. Perintah ini mencetak tiga baris Saved note, lalu, terakhir:
    Imported 3 notes.
    Tanpa input sama sekali, perintah ini hanya mencetak:
    Imported 0 notes.

Coba: klik tombol Input di sebelah Run. Sebuah kotak terbuka di bawah argumen. Ketik tiga baris di dalamnya, dengan satu baris kosong di antara dua baris. Ketik import di kotak setelah $ node notes.js lalu tekan Enter. Kemudian kosongkan kotak Input dan jalankan import lagi: kamu akan melihat Imported 0 notes..

Coba sendiri

// Alat catatanmu dimulai di sini.
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);
}

Semua pelajaran di Dasar-Dasar Node.js

Latihan sendiri: Playground Express