简体   繁体   中英

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. 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. This generates an error:

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

This is my 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.

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. If your JSON file which stores the schema does not change so often, this method might be useful.

If you want to load your JSON file from disk every time, not from cache. Use fs :

var fs = require('fs');

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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