内置模块
本课属于 Coddy Node.js 学习旅程的“Node.js 基础”单元。第 9 课,共 33 课。
你的笔记很快就会保存在文件中,而文件路径因电脑而异。
Node 自带处理这些问题的模块。你可以像导入自己的文件一样导入它们,使用 node: 前缀,无需安装任何东西。path.join 会用正确的分隔符拼接路径的各个部分,path.basename 会返回最后一部分,os.homedir() 是你的主文件夹,而 process.cwd() 是程序运行所在的文件夹。
import os from 'node:os';
import path from 'node:path';
const file = path.join(os.homedir(), 'photos', 'cat.png');
console.log(file); // /home/ada/photos/cat.png
console.log(path.basename(file)); // cat.pngpath.join 会在各部分之间放一个斜杠,因此你永远不会得到 photoscat.png。
挑战
简单- 一个新的
where命令会打印当前文件夹中notes.json的完整路径:path.join(process.cwd(), 'notes.json')。 - 第二行会打印该路径的基本名称。
运行 node notes.js where。文件目前还不存在:第 3 章会创建它。
亲手试试
// 你的笔记工具从这里开始。
import { formatNote } from './format.js';
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(`Adding: ${formatNote(n, 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');
}
store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} else {
if (command) {
console.error(`Unknown command: ${command}`);
}
console.error('Usage: node notes.js <command> [words]');
process.exit(1);
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Node.js 基础中的所有课
自己练习: Express 在线编辑器