简体   繁体   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

I am trying to use fs.writeFile to loop from an array of strings to create a new text file.我正在尝试使用 fs.writeFile 从字符串数组中循环以创建新的文本文件。 I use fs.writeSync and it worked.我使用 fs.writeSync 并且它有效。 However, when I use fs.writeFile, the content in the text file that I created does not show every item in my array.但是,当我使用 fs.writeFile 时,我创建的文本文件中的内容并未显示数组中的每个项目。 Instead, the result is more like some incomplete strings of my array.相反,结果更像是我的数组的一些不完整的字符串。 I use the setTime() function to set it for 3 seconds and still does not show complete results in my text file.我使用 setTime() function 将其设置为 3 秒,但仍然没有在我的文本文件中显示完整的结果。

The fs.writeSync one works perfectly 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')

My current output:我目前的 output:

Manage your stress s and emotions ence isn't a fixed trait管理你的压力和情绪并不是一个固定的特质

The way writeFile is working is that it is not appending to the file but rather replacing the text in it. writeFile 的工作方式是它不是附加到文件,而是替换其中的文本。 This is the reason for the output you get.这就是你得到 output 的原因。

You can instead use the function appendFile.您可以改用 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 will write the given content into the file, resulting in overwritting the existing content of the file. fs.writeSync会将给定的内容写入文件,从而覆盖文件的现有内容。

If you wish to append to the file you should use fs.appendFileSync for the purpose.如果你希望 append 到文件中,你应该使用fs.appendFileSync来达到目的。

Before that, a quick tip:在此之前,快速提示:

You should check if the directory/file is already present or not and then create a new directory if one is not present.您应该检查目录/文件是否已经存在,如果不存在则创建一个新目录。

You can do this with fs.ensureDirSync(dir) and fs.mkdirSync(dir)您可以使用fs.ensureDirSync(dir)fs.mkdirSync(dir)执行此操作

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

Now, you can use fs.appendFileSync to append to your file.现在,您可以使用fs.appendFileSync到 append 到您的文件。

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

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

The main concept to note here is, any write file operation will replace the file and content whereas, append file operation will append the content at the end of the file.这里要注意的主要概念是,任何写入文件操作都将替换文件和内容,而 append 文件操作将 append 文件末尾的内容。

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

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