如何使用socket.io和node.js将数据写入JSON文件?
我想从用户获取数据,并使用以下代码将其写入到我的json文件中:
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'); }); }); }); };
我的控制台中有一条消息:“写入文件的数据”。 但是我的./list.json
仍然是空的。 为什么? 我的websocket.js
文件和list.json
放在同一个文件夹中。
问题是一条路。
fs.writeFile(__dirname +'/list.json', data, (err) => { if (err) throw err; console.log('Data written to file'); });