删除笔记
本课属于 Coddy Node.js 学习旅程的“Node.js 基础”单元。第 15 课,共 33 课。
done 2 应该删除便笺 2,而人们会在 done 后输入任意内容。
参数都是字符串:Number('2') 是 2,Number('two') 是 NaN。Number.isInteger 会在一次检查中排除 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 命令,按编号移除笔记。
- 在
notes.js中添加一个done命令。done后面的单词是笔记编号,与list显示的编号一致,所以笔记 1 是第一条笔记。这个单词会以字符串形式传入。 - 从存储中移除这条笔记,然后将笔记保存到
notes.json,保存方式与add相同。笔记 1 在数组中的索引是 0。你可以把移除代码写在notes.js中,也可以将它写成store.js中的方法。 - 输出
Done:,后面跟上被移除笔记的内容。如果笔记是Buy milk、Call Ada和Water the plants,运行node notes.js done 1会输出:然后,Done: Buy milknotes.json中只保留Call Ada和Water the plants。done 3会移除Water the plants。 - 如果这个单词不是某条笔记的编号,就不要更改任何内容。向 stderr 输出
No note,后面跟上这个单词,并以代码 1 退出。这适用于abc、0、2.5这样的十进制数,以及超出笔记数量的编号,例如有三条笔记时输入9。运行node notes.js done abc会以红色输出:No note abc
试试看:在 $ node notes.js 后面的输入框中输入 list,查看你的笔记和编号。输入 done 1,然后再次输入 list:第一条笔记消失了,其他笔记的编号都向前移动了一位。然后输入 done abc:你会看到红色的 No note abc,退出代码为 1,而且 list 显示的笔记与之前相同。
亲手试试
// 你的笔记工具从这里开始。
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);
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Node.js 基础中的所有课
自己练习: Express 在线编辑器