ノートの削除
CoddyのNode.jsジャーニー「Node.jsの基礎」セクションの一部。レッスン 12/24。
done 2 を実行するとメモ 2 が削除され、利用者は done の後に任意の内容を入力します。
引数は文字列です。Number('2') は 2 になり、Number('two') は NaN になります。Number.isInteger は 1 回のテストで NaN と 2.5 を拒否します。その後、範囲を確認します。リストは 1 から数え、配列は 0 から数えるため、メモ n はインデックス n - 1 にあり、splice(i, 1) で削除できます。
// node seat.js 4
const seat = Number(process.argv[2]);
if (!Number.isInteger(seat) || seat < 1 || seat > 30) {
console.error(`No seat ${process.argv[2]}`);
process.exit(1);
}
console.log(`Row ${Math.ceil(seat / 6)}`);チャレンジ
簡単done <n>はメモ n を削除して保存し、Done: <text>を出力します。- メモではない単語(
abc、0、2.5、末尾を超える数値)を指定すると、標準エラー出力にNo note <word>を出力して1で終了し、何も変更しません。
done 1 を実行してから、list を実行します。次に、done abc を試してください。
自分で試してみよう
// メモツールはここから始まります。
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(' ');
if (command === 'add') {
const n = store.add(text);
console.log(`Saved note ${n}.`);
} 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');
}
store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} 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 === '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);
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。