在 javascript 中,如何使用 fs.writeFile 并循环数组并在新文本文件中垂直完整打印数组中的每个项目

In javascript, how do I use fs.writeFile and loop an array and completely print each item from the array vertically in a new text file

我正在尝试使用 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')

我当前的输出:

管理压力 s和情绪 ence 不是一个固定的特征

writeFile 的工作方式是它不是附加到文件而是替换文件中的文本。这就是您获得输出的原因。

您可以改为使用函数 appendFile。

function fileWrite2(savePath) {
    setTimeout(() => {
        for (var i = 0; i < tips.length; i++) {
            fs.appendFile(savePath, tips[i] + "\n", function(err) {
                if (err) throw err;
            });
        }
        console.log('File written sucessfully');
    }, 3000);
}

fs.writeSync 会将 给定的内容 写入文件,导致覆盖文件的现有内容。

如果您希望附加到文件中,您应该使用 fs.appendFileSync

在此之前,快速提示:

You should check if the directory/file is already present or not and then create a new directory if one is not present.

您可以使用 fs.ensureDirSync(dir)fs.mkdirSync(dir)

if (!fs.ensureDirSync(dir)) {
    fs.mkdirSync(dir);
}

现在,您可以使用 fs.appendFileSync 附加到您的文件。

fs.appendFileSync(dir, 'your data!', function(err){
    if(err)
      return err;

    console.log("file saved successfully");
});

这里要注意的主要概念是,任何写文件操作都会替换文件和内容,而追加文件操作会将内容追加到文件末尾。