Thursday, October 20, 2022

[FIXED] How to write a file using LF instead of CRLF on Windows?

Issue

We have a script that runs as the preinstall script. It uses fs.writeFile to write a config file which it generates.

writeFile(configFilePath, configFileContents, (e) => {
    // ... do some error handling
}

For some reason it uses CRLF line endings on Windows and creating diffs in git although the file has not changed.

I have tried to do use

.replace(/\r\n/gm, "\n");

on configFileContents but it still uses the Windows line endings.

configFileContents gets created by:

const configFileContents = JSON.stringify({
  foo: bar,
  baz, foo,
  // ...
}, null, 2);

Is there a way to tell Node to use the Linux ones?


Solution

You can simply do this:

.replace(/\r\n/g, "\n")

Also /\r\n/gm regexp isn't correct as you're already telling the Regexp engine to look for new line by providing the m/multiple lines option... That's why it doesn't allow the expression to work. Just use g if you really wan't to use the RegExp



Answered By - KR Tirtho
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.