繁体   English   中英

写入JSON文件(使用Node.js在Localhost服务器上工作)

[英]Writing to a JSON file (Using Node.js to work on a Localhost server)

所以我使用的是C3.js,一个建立在广泛使用的D3.js可视化库之上的图表库。 因此,作为我使用图表创建的网页的一部分,我想要包含一个用户交互,用户可以在其中输入新对象的值,该对象可以与已经通过表格上的表格绘制的当前对象一起绘制。 HTML页面。 我正在使用JSON数据作为正在读入图表的文件格式。 我想知道如何从javascript代码写入/更新此文件,以便数据现在包含新对象。 由于我是基于Web的技术的新手,我不太清楚如何在服务器上更新数据。 服务器是由文件app.js创建的本地主机,该文件创建节点服务器。

var express = require('express');
var http = require('http');
var app = express();


app.use(express.static(__dirname + '/public'));

server = http.createServer(app);
server.listen('14000');

我将app.js的上述代码作为参考包含在内,如果这有任何区别的话。 json文件的文件格式如下所示......

[
      {name: "Lane Warner",age: 27,height: 231,weight: 120},
      {name: "Hickman Bishop",age: 29,height: 125,weight: 180},
      {name: "Tracy Sheppard",age: 30,height: 200,weight: 155},
      {name: "Madeleine Spence",age: 30,height: 179,weight: 112},
      {name: "Alicia Beasley",age: 36,height: 300,weight: 200},
      {name: "Bryant Fitzpatrick",age: 23,height: 321,weight: 250},
      {name: "Stevenson Mcdonald",age: 30,height: 155,weight: 199},
      {name: "Hannah Ratliff",age: 21,height: 189,weight: 136},
      {name: "Alexandra Williamson",age: 39,height: 258,weight: 123}
]

您可以使用fs.readFile模块从文件中读取,使用JSON.parse来解析JSON。

JSON-util.js中:

var fs = require('fs');

module.exports.loadJson = function (file, callback) {
  fs.readFile('file.json', { encoding: 'utf8' }, function (err, data) {
    if (err) return callback(err); // file reading error
    try {
      // parse and return json to callback
      var json = JSON.parse(data);
      callback(null, json);
    } catch (ex) {
      // catch JSON parsing errors so your app doesn't crash
      callback(ex);
    }
  });
};

如果要同步读取json文件,还可以使用json = require('file.json') 请注意, require()是相对于当前文件的,而fs.readFile()是相对于cwd的。

相反,您可以使用JSON.stringifyfs.writeFile将JSON重写到该文件:

module.exports.writeJson = function (file, json, callback) {
  fs.writeFile(file, JSON.stringify(json), callback);
};

还要记住任何并发问题,例如两个请求尝试同时修改同一文件的位置。 像这样的时间表会很糟糕:

  1. 请求A读取JSON。
  2. 请求B读取JSON。
  3. 请求A将一个项添加到数组并重写JSON。
  4. 请求B将一个项添加到数组并重写JSON。

在这种情况下,请求B将完全删除添加请求A.为避免这种情况,最好始终只在内存中有一个JSON副本,并在每次修改时重写它。 我认为这超出了你的问题的范围,但想指出它。

如果你不关心并发,你可以有这样的应用程序:

app.js:

var express = require('express');
var http = require('http');
var app = express();

// if you're using Express 4.x, bodyParser is no longer built-in
var bodyParser = require('body-parser');

// here we import the file which has our loadJson and writeJson functions
var jsonUtil = require('./json-util.js');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

app.post('/additem/:id', function (req, res, next) {
  // turn ID into a file name, and be careful not to expose security holes
  var filename = idToFileName(req.params.id);
  jsonUtil.loadJson(filename, function (err, json) {

    // TODO: make sure you handle errors
    // if err is not null, you can either consider it an error, or
    // you could simply say json = [] and start a new file

    // should also do validation checks like if(json instanceof Array) and
    // verify that req.body exists and is properly formatted, etc

    json.push(req.body); // push the object from the request body into the array

    // re-save the file
    jsonUtil.writeJson(filename, json, function (err) {
      if (err) next(err);
      else res.send(200);
    });
  });
});

server = http.createServer(app);
server.listen('14000');

然后,一个看起来像这样的请求:

POST /additem/1
Content-Type: application/json

{ "name": "Alexandra Williamson", "age": 39, "height": 258, "weight": 123 }

将追加到json文件id = 1映射到的数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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