2

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.

6
  • what do you get when you console.log() the data Commented Sep 3, 2017 at 17:26
  • Try passing some static data as data Commented Sep 3, 2017 at 17:28
  • @turmuka clear json {"name": "John", "age": "25"}, etc Commented Sep 3, 2017 at 17:28
  • @Rayon tried: {"data":"asd"}. Isn't working... Commented Sep 3, 2017 at 17:30
  • 1
    Run node inspect yourfile.js and check your code line by line ( enter next) Commented Sep 3, 2017 at 17:41

1 Answer 1

1

The problem was with a path.

        fs.writeFile(__dirname +'/list.json', data, (err) => {  
            if (err) throw err;
            console.log('Data written to file');
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.