我试图将数据添加到现有的json文件(下面的代码)。当我访问locahost时,会显示新的数据,但是,当我检查数据(users.json)时,新的数据(即user4)就不存在了。
有谁知道代码有什么问题?谢谢!
var express = require('express');
var app = express();
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end( JSON.stringify(data));
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
编辑:
我添加了fs.writeFile(...)
(下面的代码)。运行代码后,uers.json文件的唯一内容是:utf8
var express = require('express');
var app = express();
var fs = require("fs");
var user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}
app.get('/addUser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
// res.end( JSON.stringify(data));
data = JSON.stringify(data);
fs.writeFile(__dirname+"/"+"users.json", "utf8", function(err,data){
if (err){
console.log(err);
};
res.end(data);
});
});
})
答案 0 :(得分:0)
要写入文件,您应使用fs.writeFile。
fs.writeFile(__dirname + "/" + "users.json", user["user4"], 'utf8', function()
{
// do anything here you want to do after writing the data to the file
});
答案 1 :(得分:0)
我已将数据传递给writeFile
,以便它可以将数据变量中的信息写入JSON
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
data = JSON.stringify(data);
fs.writeFile(__dirname + "/" + "users.json", data , 'utf8', function(err,data) {
if (err){
console.log(err);
};
res.end(data);
});
});