与 console.log 相比,用 fs.writeFile 写入的文件有额外的新行。为什么?

Files written with fs.writeFile have extra new lines compared to console.log. Why?

我有以下代码:

async function writeFile(path: string, content: string): Promise<void> {
  console.log(content);
  try {
    await fs.writeFile(path, content, "utf8");
  } catch (err) {
    reject(err);
  }
}

console.log 打印

<?xml version="1.0" encoding="utf-8"?>
<?tgml 2.0?>

<Tgml Height="10" Stretch="Uniform" Width="10">
  <Layer Stroke="None" Fill="#000000" Name="viewbox-clip">
    <Translate X="5" Y="5"/>
    <Rectangle Height="10" Left="0" Top="0" Width="10"/>
    <Ellipse Fill="#FFFFFF" Height="8" Left="1" Top="1" Width="8"/>
  </Layer>
</Tgml>

打开写入的文件(至少在 Sublime Text 或记事本中)显示:

<?xml version="1.0" encoding="utf-8"?>
<?tgml 2.0?>



<Tgml Height="10" Stretch="Uniform" Width="10">

  <Layer Stroke="None" Fill="#000000" Name="viewbox-clip">

    <Translate X="5" Y="5"/>

    <Rectangle Height="10" Left="0" Top="0" Width="10"/>

    <Ellipse Fill="#FFFFFF" Height="8" Left="1" Top="1" Width="8"/>

  </Layer>

</Tgml>

以下是关于我的环境的信息,以防与问题相关:Windows,控制台记录到 PowerShell

一种可能的解释可能是您的数据出于某种原因包含 \r\r\n 换行符,并且您的终端将这些换行符解释并打印为单个换行符。但是,编辑器多显示了一行,导致出现了两个换行符。

作为解决方法并验证是否属于这种情况,您可以在将 content 写入文件之前使用以下内容替换那些非法换行符:

content = content.replace(/\r\r\n/g,"\r\n");