简体   繁体   中英

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.

The problem was with a path.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM