0

I want json stream stored in text file. When running the node server, the json file isn't appended to the json.txt file. What am I missing? Am new to to node, so be gentle..

Here is a code chunk I expect to capture the json content:

var fs = require('fs');
fs.writeFile("json.txt",{encoding:"utf8"}, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
Antex
  • 1,364
  • 4
  • 18
  • 35
  • maybe a duplicate of [this question](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – Jthorpe May 31 '17 at 16:05
  • Possible duplicate of [How to append to a file in Node?](https://stackoverflow.com/questions/3459476/how-to-append-to-a-file-in-node) – ponury-kostek May 31 '17 at 16:05

1 Answers1

1

The issue is you aren't using the correct parameters. When calling fs.writeFile it expects a string for the filename, a buffer or string for the content, an object for the options and a callback function. What it looks like you're doing is sending the options as the second parameter when it expects a buffer or a string. Correction below;

var fs = require('fs');
fs.writeFile("json.txt", JSON.stringify({some: object}), {encoding:"utf8"}, function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

You can replace the JSON.stringify part with some plain text if you wanted to, but you specified JSON in your question so I assumed you wanted to store some object in a file

Source (NodeJS documentation)

EDIT: The links to other questions in the comments may be more relevant if you want to add new lines to the end of the file and not completely overwrite the old one. However I made the assumption that fs.writeFile was the intended function. If that wasn't the intention, those other questions will help a lot more

UPDATE:

It seems the issue was the fact that the body wasn't being parsed, so when the POST request was going through, Node didn't have the request body. To alleviate this, during the express configuration, the following code is needed:

var bodyParser = require('body-parser');
app.use(bodyParser.json());

Uses the npm module body-parser. This will convert the JSON body to a JavaScript object, and it is accessible via req.body.

Chifilly
  • 317
  • 3
  • 11
  • The scenario is that I am listening to HTTP POST from a server that is POSTING JSON - I want to capture the "raw JSON' and store it in json.txt file. I have slightly adjusted your script to this: app.post('/incomingPOST', function(req, res){ var obj = { table: [] }; var jsonp = JSON.stringify(obj); var fs = require('fs'); fs.writeFile("json.txt", jsonp , {flag: 'a'}, function(err) { if(err) { console.log(err); } else { console.log("The file was saved!"); } }) }); It is appending a file with empty JSON data. – Antex May 31 '17 at 17:47
  • I'm not sure what's happening honestly. I tested your exact code on a bare-bones test app and it worked fine. It created a `json.txt` file at my project root with `{"table":[]}` in it. If you simplified the code, try sharing exactly what you have, because the example you gave in your comment works for me. If it wasn't simplified, then maybe something else is interfering – Chifilly May 31 '17 at 18:01
  • I get the same. Instead of the {"table":[]} - I want the JSON from the server saved. Not exactly sure what the obj should be setup for that to happen? I am beginner at this - sorry if this is supposed to be obvious. – Antex May 31 '17 at 18:19
  • Okay, I see. So when you POST the JSON, you want to save the body of the request into a file. I think I know your issue (caught me out a couple of times). When you declare express and do all its setup, make sure you have `app.use(bodyParser.json());`. This will convert the body of a POST request into JSON. You will require the [`body-parser`](https://www.npmjs.com/package/body-parser) module for this. You will then be able to access the request body with `req.body` and it will be a JavaScript object. If that fixes it, I'll update my answer – Chifilly May 31 '17 at 18:22
  • you got my question accurately now . I got body-parser module installed. Still not seeing the raw JSON stored...here is my latest script...var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.post('/incomingPOST', function(req, res){ var jsonfile = require('fs'); var file = '/tmp/data.json' var jsoned = JSON.parse(req.body.data); jsonfile.writeFile(file, jsoned, {flag: 'a'}, function (err) { console.error(err); }) }); – Antex May 31 '17 at 18:52
  • The line `var jsoned = JSON.parse(req.body.data);` should be `var jsoned = JSON.stringify(req.body.data);` since `req.body.data` is already an object, then you want to stringify it so `fs.writeFile` can put the string in the file – Chifilly May 31 '17 at 18:59
  • 1
    You will need to compare the secret before the stringify, since when you stringify it turns the JSON into a string, or you could do the comparison on the full `req.body.data.secret` (but the former is probably the more readable code) – Chifilly May 31 '17 at 20:05
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145584/discussion-between-chifilly-and-antex). – Chifilly May 31 '17 at 20:10