我正在尝试使用 fs.writeFile 从字符串数组中循环以创建新的文本文件。我使用 fs.writeSync 并且它起作用了。但是,当我使用 fs.writeFile 时,我创建的文本文件中的内容并未显示数组中的每个项目。相反,结果更像是我数组的一些不完整的字符串。我使用 setTime() 函数将其设置为 3 秒,但仍然没有在我的文本文件中显示完整的结果。
fs.writeSync 一个完美的作品
function fileWriteSync(filePath) {
const fd = fs.openSync(filePath, 'w');
for (var i = 0; i < tips.length; i++) {
fs.writeSync(fd, tips[i] + '\n');
console.log(tips[i]);
}
fs.closeSync(fd);
}
tips = [
"Work in teams",
"get enough sleep",
"be on time",
"Rely on systems",
"Create a rough weekly schedule",
"Get rid of distractions before they become distractions",
"Develop good posture",
"Don’t multitask",
"Cultivate the belief that intelligence isn’t a fixed trait",
"Work in short blocks of time", "Exercise regularly",
"Be organized", "Break big tasks into smaller ones",
"Take notes during class", "Ask lots of questions",
"Eat healthily",
"Do consistent work",
"Manage your thoughts and emotions",
"Give yourself rewards",
"Manage your stress"
]
function fileWrite2(savePath) {
setTimeout(() => {
for (var i = 0; i < tips.length; i++) {
fs.writeFile(savePath, tips[i] + "\n", function(err) {
if (err) throw err;
});
}
console.log('File written sucessfully');
}, 3000);
}
fileWrite2('tips3.txt')
我目前的输出:
管理你的压力和情绪不是一个固定的特征
动漫人物
白猪掌柜的
相关分类