1

I'm trying to save output to a file. I can see the error message from server in console.log (see bellow) but for some reason it's not written in file. The file is empty. Any ideas?

const fileName = `response ${data.item.name}.json`; // create file from response of each request 
const content = data.response.stream.toString(); // content of response   
console.log("JSON response: ", content);


fs.writeFile(fileName, content, function(error) { // The file itself
  if (error) {
    console.error(error);
  }
});

What I see in console log: I need that "JSON response" be in file

→ Create pce_test
  POST http://<<server>>:<<port>>/apiv2/servers  JSON response:  Error creating Integration Server: server name in use
[409 Conflict, 886B, 82ms]

OUtput in visual studio

epascarello
  • 204,599
  • 20
  • 195
  • 236
xbath
  • 21
  • 2
  • Does this answer your question? [node - fs.writeFile creates a blank file](https://stackoverflow.com/questions/31572484/node-fs-writefile-creates-a-blank-file) – node_modules Sep 30 '22 at 12:53
  • @epascarello I've tried fs.writeFileSync too. No success. This happens just in one case, otherwise I am able to write into file. There must be problem somewhere else. – xbath Sep 30 '22 at 13:01
  • So what is special about this "case" then? – CBroe Sep 30 '22 at 13:04
  • My guess is you need to show us more code than what you have shown us. – epascarello Sep 30 '22 at 13:16
  • Seems like you already have the file under that name try to delte the file before creating or try unique name – Mohamed Anser Ali Sep 30 '22 at 20:30

1 Answers1

0

The content has to be in the JSON format, if you want to write a JSON file.

const content = `{"key": "${data.response.stream.toString()}"}`; // content of response

If you want to write the object properties in a new line with a tab, you can use something like below;

const content = JSON.stringify(`{\n \t "key": "${data.response.stream.toString()}"\n}`); 
fs.writeFile(fileName, JSON.parse(content), (error) => { // The file itself
  if (error) {
    console.error(error);
  }
});
PrasadB
  • 57
  • 1
  • 6