2

I'm reading information from a api which returns text in JSON format. I want to take that text and write it to a file. When I do it writes it with a \ in front of everything looks like this .

[{ \"ElementA":\"ValueA" ... }] 

Here's what I've tried

var info = [] request('someApi', function(err, res, body) { if (err) { return console.log('Error:', err); } if (res.statusCode != 200) { return console.log('Invalid:' + res.statusCode); } info = JSON.stringify(body); fs.writeFile('public/file', info); }); 

Also the file that I'm trying to write to is .JS if that makes any difference. My desired output is :

 [{ "ElementA": "Value A ...}] 

1 Answer 1

4

As the data which you are trying to write is already a well formed JSON, you don't have to JSON.stringify it and you can simply write it as it is, like this

fs.writeFile('public/file', body, callbackFunction); 

Note: fs.writeFile is an async function. You need to pass the callback function as well, which will be invoked when the actual writing is completed.

Sign up to request clarification or add additional context in comments.

1 Comment

You can use fs.writeFileSync is synchronicity is important.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.