Angry B
Angry B

Reputation: 305

How to write data to JSON file with socket.io and node.js?

I want to get data from the user and write it to my json file with the following code:

var fs = require('fs');


module.exports = function (io) {
    io.on('connection', function (socket) {
        socket.on("search list", function(search_data){

            // write my object to JSON document
            let data = JSON.stringify(search_data); // {"name": "John", "age": "25"}             

            fs.writeFile('./list.json', data, (err) => {  
                if (err) throw err;
                console.log('Data written to file');
            });

        });
    });
};

I have a message in my console: "Data written to file". But my ./list.json still empty. Why? My websocket.js file and list.json are placed in the same folder.

Upvotes: 2

Views: 2003

Answers (1)

Angry B
Angry B

Reputation: 305

The problem was with a path.

        fs.writeFile(__dirname +'/list.json', data, (err) => {  
            if (err) throw err;
            console.log('Data written to file');
        });

Upvotes: 1

Related Questions