如何将多行写入循环中的文本文件?

发布于 2025-02-09 15:04:03 字数 675 浏览 1 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

芸娘子的小脾气 2025-02-16 15:04:03

根据文档):

异步将数据写入文件,如果文件已经存在,则替换文件。
...
在同一文件上多次使用filehandle.writefile()而不等待应许被解决(或拒绝)。

是不安全的。

您每次都会在解决承诺之前调用writefile来覆盖文件。相反,我认为最简单的方法是将您的文本写入中间对象data< string> | |< |< | |> |< typedarray> | | |< dataveiew< object>),然后filehandle.writefile(data)在最后。

According to the documentation for fs.writeFile():

Asynchronously writes data to a file, replacing the file if it already exists.
...
It is unsafe to use filehandle.writeFile() multiple times on the same file without waiting for the promise to be resolved (or rejected).

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 object data (<string> | <Buffer> | <TypedArray> | <DataView> | <Object>) and then filehandle.writeFile(data) at the end.

寻找我们的幸福 2025-02-16 15:04:03

使用 fspromises.appendfile每次文件而不是每次覆盖它:

./ main.mjs

import {appendFile, readFile} from 'fs/promises';

const SESSIONS_PATH = './sessions_data';

// Append to the file instead of overwriting the entire file
const outputMonthlySessions = (content) => appendFile(SESSIONS_PATH, content);

async function main () {
  const start = 'now';
  const end = 'later';

  const events = [
    {
      summary: 'first',
      start: { date: start },
      end: { dateTime: end },
    },
    {
      summary: 'second',
      start: { dateTime: start },
      end: { date: end },
    },
  ];

  for (const event of events) {
    const start = event.start.dateTime || event.start.date;
    const end = event.end.dateTime || event.end.date;
    await outputMonthlySessions(`${event.summary}: ${start} - ${end} \n`); /*
    ^^^^^
    Await the promise before continuing to the next loop iteration */
  }

  const text = await readFile(SESSIONS_PATH, {encoding: 'utf8'});
  console.log(text.split('\n'));
}

main();

在终端:

so-72718707 % node --version  
v16.15.1

so-72718707 % node main.mjs    
[ 'first: now - later ', 'second: now - later ', '' ]

Use fsPromises.appendFile to append to the file each time instead of overwriting it every time:

./main.mjs:

import {appendFile, readFile} from 'fs/promises';

const SESSIONS_PATH = './sessions_data';

// Append to the file instead of overwriting the entire file
const outputMonthlySessions = (content) => appendFile(SESSIONS_PATH, content);

async function main () {
  const start = 'now';
  const end = 'later';

  const events = [
    {
      summary: 'first',
      start: { date: start },
      end: { dateTime: end },
    },
    {
      summary: 'second',
      start: { dateTime: start },
      end: { date: end },
    },
  ];

  for (const event of events) {
    const start = event.start.dateTime || event.start.date;
    const end = event.end.dateTime || event.end.date;
    await outputMonthlySessions(`${event.summary}: ${start} - ${end} \n`); /*
    ^^^^^
    Await the promise before continuing to the next loop iteration */
  }

  const text = await readFile(SESSIONS_PATH, {encoding: 'utf8'});
  console.log(text.split('\n'));
}

main();

In the terminal:

so-72718707 % node --version  
v16.15.1

so-72718707 % node main.mjs    
[ 'first: now - later ', 'second: now - later ', '' ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文