2

I am implementing a NodeJS script which auto-generates JavaScript code.

I need to write "xxx\n" somewhere in the auto-generated JavaScript file.

But I want the \n part to be OS-compatible.

I've figured I should use require("os").EOL, for example:

let EOL = require("os").EOL;
let str = `xxx${EOL}`;
...
// write str into the file

But that writes a real newline into the file.

How can I convert that EOL into an actual string, like "\n" or "\r\n"?

P.S.:

For performance considerations, I wish to avoid plugging require("os").EOL into the auto-generated file (i.e., I want the newline to be "hard-coded" in there).

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • 1
    `JSON.stringify(require("os").EOL).slice(1, -1)`, but this does seem an odd thing to do. – Keith Jun 29 '18 at 09:04
  • UNIX master race, who cares about CRLF – Isaaс Weisberg Jun 29 '18 at 09:05
  • Just an idea, you could check what EOL is, like `if(EOL === "\r\n") { str = 'xxx\r\n'; } elseif ...` and so on. Bit hacky ... ;) – eisbehr Jun 29 '18 at 09:07
  • @eisbehr Also you of course meant, -. `xx\\r\\n` – Keith Jun 29 '18 at 09:08
  • @Keith: That's a pretty neat idea!!! – goodvibration Jun 29 '18 at 09:08
  • @Keith: Yes, I did (I mean, at present, I am using `"\\n"` in my auto-generating script). – goodvibration Jun 29 '18 at 09:09
  • https://github.com/ryanve/eol uses `isWindows = typeof process != 'undefined' && 'win32' === process.platform`. Would that be viable? – KooiInc Jun 29 '18 at 09:09
  • @KooiInc: That would be rather nasty IMO. I prefer not to plug "windows related" code into my script. What if there's another OS out there with the same properties but a different newline sequence? – goodvibration Jun 29 '18 at 09:11
  • @goodvibration, I agree. Another question may be why line endings in javascript (albeit generate) are actually relevant? – KooiInc Jun 29 '18 at 10:11
  • Possible duplicate of [Javascript - How to show escape characters in a string?](https://stackoverflow.com/questions/21672334/javascript-how-to-show-escape-characters-in-a-string) – jannis Jun 29 '18 at 10:27

0 Answers0