简体   繁体   English

如何在我的node.js应用中读取json文件?

[英]How to read a json file in my node.js app?

I have a simple node.js service where I perform some json validation against a schema defined in jsonSchema. 我有一个简单的node.js服务,其中我对jsonSchema中定义的模式执行一些json验证。 The service looks like: 该服务看起来像:

app.post('/*', function (req, res) {
        var isvalid = require('isvalid');
        var validJson=true;
        var schema = require('./schema.json')
        isvalid(req.body,schema
            , function(err, validObj) {
                if (!validObj) {
                    validJson = false;
                }
                handleRequest(validJson,res,err,req);
            });
})

Trying to use the direct require statement in the 4th line above. 尝试使用上面第四行中的直接require语句。 This generates an error: 这会产生一个错误:

SyntaxError: c:\heroku\nodejs_paperwork\schema.json: Unexpected token t

This is my schema.json: 这是我的schema.json:

{
  type: Object,
  "schema": {
    "totalRecords": {
      type: String
    },
    "skip": {
      type: Number
    },
    "take": {
      type: Number
    }
}

You may have overlooked. 您可能已经忽略了。 You can just load and parse it with require statement. 您可以使用require语句加载并解析它。

var jsonData = require('/path/to/yourfile.json');

However, the output from the method above is cached, once you update your JSON file and load it with require again, it loads the content from cache. 但是,上述方法的输出将被缓存,一旦您更新了JSON文件并再次将其加载为require,它就会从缓存中加载内容。 If your JSON file which stores the schema does not change so often, this method might be useful. 如果存储模式的JSON文件不经常更改,则此方法可能有用。

If you want to load your JSON file from disk every time, not from cache. 如果您想每次从磁盘而不是从缓存加载JSON文件。 Use fs : 使用fs

var fs = require('fs');

fs.readFile(filepath, 'utf8', function (err, data) {
  if (err) {
    // handle error
    return;
  }

  jsonData = JSON.parse(data); 
});

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

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