搜索
本课属于 Coddy Node.js 学习旅程的“Node.js 基础”单元。第 32 课,共 33 课。
有几十条笔记时,滚动浏览 list 就不管用了:你需要搜索。
比较之前,先把两边都转换成小写,这样 Milk、milk 和 MILK 都能匹配,然后用 includes 检查。遍历整个列表并保留每个索引,这样匹配结果显示的编号就和 list 中的一样,也是 done 和 remind 所需要的编号。
const songs = ['Blue Moon', 'Moonlight', 'Sunny'];
const query = 'MOON'.toLowerCase();
songs.forEach((title, i) => {
if (title.toLowerCase().includes(query)) {
console.log(`${i + 1}. ${title}`);
}
});挑战
简单笔记很多时,翻阅 list 就不方便了。添加一个 search 命令,按词查找笔记。
- 在
notes.js中添加search命令。search后面的词就是要查找的内容。 - 找出包含搜索文本的所有笔记,不区分大小写:
milk、Milk和MILK都能找到Buy milk。 - 使用
formatNote打印每条匹配结果,并使用笔记在list中的编号,这样你就可以用这个编号执行done和remind。按笔记的存储顺序从最早到最新打印匹配结果,即使settings.json会让list按最新到最早排序也一样。不要打印标题。
如果笔记是 Buy milk、Call Ada 和 buy bread,运行 node notes.js search buy 会打印:
1. Buy milk
3. buy bread运行 node notes.js search ADA 会打印 2. Call Ada。
- 没有匹配的笔记时,打印
No notes match,后面跟上搜索文本。运行node notes.js search tea会打印:No notes match tea
试试看:在 $ node notes.js 后面的输入框中输入 search milk 并按 Enter,然后输入 search MILK:两次都会找到相同的笔记。然后搜索一个不在任何笔记中的词:你会看到 No notes match 和那个词。
亲手试试
// 你的笔记工具从这里开始。
import { rmSync } from 'node:fs';
import path from 'node:path';
import { formatNote } from './format.js';
import stats from './legacy/stats.cjs';
import pkg from './package.json' with { type: 'json' };
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 === 'import') {
let input = '';
for await (const chunk of process.stdin) {
input += chunk;
}
const lines = input
.split('\n')
.map((line) => line.trim())
.filter((line) => line !== '');
for (const line of lines) {
await store.add(line);
}
console.log(`Imported ${lines.length} notes.`);
} else if (command === 'version') {
console.log(`${pkg.name} ${pkg.version}`);
} 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 在线编辑器