繁体   English   中英

在 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() function 将其设置为 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')

我目前的 output:

管理你的压力和情绪并不是一个固定的特质

writeFile 的工作方式是它不是附加到文件,而是替换其中的文本。 这就是你得到 output 的原因。

您可以改用 function 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会将给定的内容写入文件,从而覆盖文件的现有内容。

如果你希望 append 到文件中,你应该使用fs.appendFileSync来达到目的。

在此之前,快速提示:

您应该检查目录/文件是否已经存在,如果不存在则创建一个新目录。

您可以使用fs.ensureDirSync(dir)fs.mkdirSync(dir)执行此操作

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM