Arka Das
Arka Das

Reputation: 37

NodeJS JSON file Read without newline characters

I am reading a JSON file using fs.readFileSync(fileName, 'utf8'); but the results include newline characters, and the output is getting like:

"{\r\n    \"name\":\"Arka\",\r\n    \"id\": \"13\"\r\n}"

How do I avoid these characters?

my local file looks like:

{
  "name":"Arka",
  "id": "13"
}

Upvotes: 1

Views: 6914

Answers (2)

peteb
peteb

Reputation: 19428

Its unnecessary to read JSON in using fs.readFileSync(). This requires you to also write a try/catch block around the fs.readFileSync() usage and then use JSON.parse() on the file data. Instead you can require JSON files in Node as if they were packages. They will get parsed as if you read the file in as a string and then used JSON.parse(), this simplifies the reading of JSON to one line.

let data = require(fileName)
console.log(data) // { name: 'Arka', id: '13' }

If you want to serialize the parsed JS object within data to a file without the new line & carriage return characters you can write the JSON string to a file using JSON.stringify() only passing in data.

const {promisify} = require('util')
const writeFile = util.promisify(require('fs').writeFile)
const data = require(fileName)

const serializeJSON = (dest, toJson) => writeFile(dest, JSON.stringify(toJson))

serializeJSON('./stringify-data.json', data)
  .then(() => console.log('JSON written Successfully'))
  .catch(err => console.log('Could not write JSON', err))

Upvotes: 6

Fabian Lauer
Fabian Lauer

Reputation: 9917

You could read the file and then remove them with a regex:

var rawJson = fs.readFileSync(fileName, 'utf8');
rawJson = rawJson.replace(/\r|\n/g, '');

Keep in mind though that for parsing JSON with JSON.parse, you don't need to do this. The result will be the same with and without the newlines.

Upvotes: 1

Related Questions