0

I have a text file and I want to send its content as a string as a response to a get request in my express app but the content already has content instances of \n in it and the node.js' readFile also adds additional \n to it which makes it hard to parse the string on the client-side. So I wanted to know that if I can change the \n added by the readFile method with something of my choice like \r or any other pattern.

File:

enter image description here

server.js

const fs = require ("fs")
const fileContents = fs.readFileSync ("./file.txt", "utf8")

output:

"This is texst \n string\nand I want to use \r instead of \n\nin it"

deAr
  • 15
  • 5
Beginner
  • 182
  • 2
  • 14
  • 2
    No it doesn't, `readFile` does not introduce anything to the file contents, the buffer you get is the data on disk. – Mike 'Pomax' Kamermans Sep 04 '21 at 16:45
  • So is there any other way to send the string without introducing \n in it? – Beginner Sep 04 '21 at 16:47
  • 2
    Nothing introduces `\n` unless the code _you_ wrote does that, so "we can't tell you, without you showing an [mcve]" really. The only one who knows what your code is doing right now is you. – Mike 'Pomax' Kamermans Sep 04 '21 at 16:48
  • I have added an example. Please take a look. – Beginner Sep 04 '21 at 16:56
  • 3
    That text file has _the letters_ \n in it, they're not special in any way, they're just plain text, so your text file is the problem here. If you want to clean up your text file, by all means, read it in, run a replacement like ```fileBuffer.toString(`utf-8`).replaceAll(`\\n`, ``)```, but that's a different from what you originally posted, and one that you can find lots of answers for on SO already. – Mike 'Pomax' Kamermans Sep 04 '21 at 16:58
  • If you need to know how to change the contents of a file in Node then this has already been answered elsewhere. – Alias Cartellano Sep 04 '21 at 16:59
  • Does this answer your question? [Replace a string in a file with nodejs](https://stackoverflow.com/questions/14177087/replace-a-string-in-a-file-with-nodejs) – Alias Cartellano Sep 04 '21 at 17:00
  • I think I will have to read the content of file line by line and replace the \n with \r in each line. – Beginner Sep 04 '21 at 17:08

0 Answers0