Я пытаюсь использовать fs.writeFile для цикла из массива строк, чтобы создать новый текстовый файл. Я использую fs.writeSync, и это сработало. Однако, когда я использую fs.writeFile, содержимое созданного мною текстового файла не отображает каждый элемент в моем массиве. Вместо этого результат больше похож на некоторые неполные строки моего массива. Я использую функцию setTime (), чтобы установить ее на 3 секунды, и все еще не показывает полные результаты в моем текстовом файле.
fs.writeSync one отлично работает
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')
Мой текущий вывод:
Управляйте своими стрессами и эмоциями, а не фиксированной чертой