我们在 TODO 模块中想要的功能之一是 CSV 导出功能。这会将我们存储的所有 TODO 连同完成的状态打印到一个文件中。这要求我们使用该fs模块——一个用于处理文件系统的内置 Node.js 模块。
写入文件是一种异步操作。在 Node.js 中有很多方法可以写入文件。我们可以使用回调、Promises 或async/await关键字。在本节中,我们将看看我们如何为这些不同的方法编写测试。
回调
回调函数是用作异步函数的参数的函数。当异步操作完成时调用它。
让我们在我们的Todos类中添加一个名为saveToFile(). 这个函数将通过遍历我们所有的 TODO 项并将该字符串写入文件来构建一个字符串。
打开你的index.js文件:
nano index.js
在此文件中,添加以下代码:
const fs = require('fs');
class Todos {
constructor() {
this.todos = [];
}
list() {
return [...this.todos];
}
add(title) {
let todo = {
title: title,
completed: false,
}
this.todos.push(todo);
}
complete(title) {
if (this.todos.length === 0) {
throw new Error("You have no TODOs stored. Why don't you add one first?");
}
let todoFound = false
this.todos.forEach((todo) => {
if (todo.title === title) {
todo.completed = true;
todoFound = true;
return;
}
});
if (!todoFound) {
throw new Error(`No TODO was found with the title: "${title}"`);
}
}
saveToFile(callback) {
let fileContents = 'Title,Completed\n';
this.todos.forEach((todo) => {
fileContents += `${todo.title},${todo.completed}\n`
});
fs.writeFile('todos.csv', fileContents, callback);
}
}
module.exports = Todos;
我