如何将多行写入循环中的文本文件?
在JavaScript函数中,我正在列出事件列表,对于每个事件,我想将文本写入文件。 在运行包含该循环的函数时,我提供了正确的内容
// Code within another function
events.map(event => {
const start = event.start.dateTime || event.start.date;
const end = event.end.dateTime || event.end.date;
outputMonthlySessions(`${event.summary}: ${start} - ${end} \n`);
});
// Function to write to file called sessions located at FILE_PATH
function outputMonthlySessions(content) {
fs.writeFile(SESSIONS_PATH, content, err => {
if (err) {
console.error(err)
}
});
}
,我只在会话文本文件上打印了1个事件,但是我应该打印10。这告诉我循环或我如何使用writefile有问题。我怀疑这与异步有关,但不确定如何格式化我的循环以使其正常工作。任何帮助将不胜感激!
Within a javascript function, I'm taking in a list of events and for each event, I would like to write text to a file. I have provided the correct
// Code within another function
events.map(event => {
const start = event.start.dateTime || event.start.date;
const end = event.end.dateTime || event.end.date;
outputMonthlySessions(`${event.summary}: ${start} - ${end} \n`);
});
// Function to write to file called sessions located at FILE_PATH
function outputMonthlySessions(content) {
fs.writeFile(SESSIONS_PATH, content, err => {
if (err) {
console.error(err)
}
});
}
When I run the function containing that loop, I only get 1 event printed on the SESSIONS text file, but I should be printing 10. That tells me something is wrong with the loop or how I'm using writeFile. I suspect it's something to do with async but then not sure how to format my loop to make it work. Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据文档):
您每次都会在解决承诺之前调用
writefile
来覆盖文件。相反,我认为最简单的方法是将您的文本写入中间对象data
(< string> | |< |< | |> |< typedarray> | | |< dataveiew< object>
),然后filehandle.writefile(data)
在最后。According to the documentation for
fs.writeFile()
:You are overwriting the file each iteration by calling
writeFile
every time, possibly before the promise is resolved. Instead, I think the simplest approach is to write your text to an intermediate objectdata
(<string> | <Buffer> | <TypedArray> | <DataView> | <Object>
) and thenfilehandle.writeFile(data)
at the end.使用
fspromises.appendfile
每次文件而不是每次覆盖它:
./ main.mjs
:在终端:
Use
fsPromises.appendFile
to append to the file each time instead of overwriting it every time:./main.mjs
:In the terminal: