如何在node.js中读取JSON文件后更新它

时间:2015-10-01 07:54:06

标签: json node.js

在app.js中,我只读取traffic.json文件,但我需要更新traffic.json文件。当我点击提交按钮时,我获取了以前的数据而不是新数据。

Area.html:

var jsonURL = "http://192.168.7.123:3000/traffic";

    d3.json(jsonURL, function(error, data){ 
alert(data);
 ....
 ....
});

app.js:

app.get('/traffic',function(req,res) {
  res.sendfile('views/traffic.json');
});

traffic.json:

[ { "client_ip" : "1.0.230.145" , "timestamp" : "1341667450773" , "total_traffic" : 0} , { "client_ip" : "1.0.230.145" , "timestamp" : "1341667450786" , "total_traffic" : 3} , { "client_ip" : "1.0.230.145" , "timestamp" : "1341667451076" , "total_traffic" : 4} , { "client_ip" : "1.0.230.145" , "timestamp" : "1341667451104" , "total_traffic" : 7} , { "client_ip" : "1.0.230.145" , "timestamp" : "1341667451128" , "total_traffic" : 10}]

如何更新traffic.json文件,以便在点击提交后获取新更新的数据?

1 个答案:

答案 0 :(得分:0)

您可JSON.stingify()使用fs.writeFile()fs.writeFileSync()

traffic.json新数据保存到var fs = require('fs'); app.get('/traffic',function(req,res) { // I don't know what information you need to save. IP of the client that clicked button? fs.writeFileSync('views/traffic.json', JSON.stringify(newData)); res.sendfile('views/traffic.json'); });
<form-login login-page="/redirect" 
        login-processing-url="/submitLogin" 
        username-parameter="j_username" 
        password-parameter="j_password" 
        authentication-failure-handler-ref="loginFailureHandler" 
        authentication-success-handler-ref="loginSuccessHandler" />

 <authentication-manager>
    <authentication-provider>
        <jdbc-user-service 
            data-source-ref="sybaseDataSource" 
            users-by-username-query="SELECT distinct EnterpriseID as username, 'password' as password, 1 as enabled FROM users where id = ?" 
            authorities-by-username-query="SELECT ? as id, 'ROLE_USER' as authority" 
           <!-- I know, it shouldnt be like this, just for the sake of the user having an authority -->
        />
    </authentication-provider>
</authentication-manager>