Reputation: 1581
I am trying to output a txt file with line breaks with the fs module in node.
Trial #1 - UTF8 Encoded
let list = req.body.L_.replace(/['"]+/g, '').replace(/\r\n/gi, '\\0x0D')
fs.writeFile('./_log/L_.replace(/\"/g, "") + '.txt', list, 'utf8', (err) => {
if (err) throw err
})
Input
"0 1 ITEM \r\n 2 2 ITEM \r\n"
Output
0 1 ITEM \u0A0 2 2 ITEM \u0A
Expected Output
0 1 ITEM
2 2 ITEM
Trial #2 - Default Node fs Encoding
let list = req.body.L_.replace(/['"]+/g, '')
fs.writeFile('./_log/L_.txt', list, (err) => {
if (err) throw err
})
Input
"0 1 ITEM \r\n 2 2 ITEM \r\n"
Output
0 1 ITEM \u0A0 2 2 ITEM \u0A0
Expected Output
0 1 ITEM
2 2 ITEM
Trial #3 - Default Node fs Encoding
let list = req.body.L_.replace(/['"]+/g, '')
fs.writeFile('./_log/L_.txt', list, (err) => {
if (err) throw err
})
Input
"0 1 ITEM \r 2 2 ITEM \r"
Output
0 1 ITEM 2 2 ITEM
Expected Output
0 1 ITEM
2 2 ITEM
Upvotes: 2
Views: 2475
Reputation: 197
Edit based on comments:
This isn't a nodejs issue. It sounds like encoding for notepad is nonexistent. I recall looking at server logs years ago with nodepad and they where all on one line too. I would suggest using a different text file reader such as Sublime or Notepad++
When I run the .replace
code you have it works fine for me. Below I have create a test string, from your example. I have escaped some of the characters that javascript would have interpreted. Then called your replace method. Which you can see that the out come was after
var s = "\"0 101 1 102 XYZ 15141 144 Test \\n\""
var s2 = s.replace(/['"]+/g, '');
// s2 is 0 101 1 102 XYZ 15141 144 Test \n
In your example you aren't calling the replace method. This leads me to believe you are calling it incorrectly. The replace method returns a new string leaving original string unaffected.
I would suggest something like this (storage is cheap)
var num = JSON.stringify(req.body.number).replace(/\"/g, "");
var list = JSON.stringify(req.body.list).replace(/['"]+/g, "");
list = list.replace(/[ ]+/g, "\t"); // Replaces the spaces with a single tab
fs.writeFile('./_log' + num + '.txt', list, (err) => {
if (err) throw err
})
Upvotes: 1