7

I tried to parse json file in node but there always error and I google it but cannot solve it . Can you help me?

undefined:1
undefined
^
SyntaxError: Unexpected token u
at Object.parse (native)
at Object.<anonymous> (app.js:13:19)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

this's my code

var app = express();
var mongodb = require("mongoskin");
var fs = require('fs');

var content;
fs.readFile('./config/db.json', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
var config = JSON.parse(content);


app.get('/', function(req, res){
    res.send(config.left);
});

app.listen(process.env.VCAP_APP_PORT || 3000);

and the db.json is this. As you can see, there are no errors.

{
  "left": 3
}
0

2 Answers 2

7

readFile is asynchronous, so your JSON.parse line is called before you assign a value to content, and so content has its default value of undefined.

You have two options:

  1. Move the logic using the data into the callback.

    var app = express();
    var mongodb = require("mongoskin");
    var fs = require('fs');
    
    fs.readFile('./config/db.json', function read(err, data) {
        if (err) {
            throw err;
        }
    
        var config = JSON.parse(data); // <=== Note I'm using `data`, not `content`; we don't need a `content` variable anymore
    
        app.get('/', function(req, res){
            res.send(config.left);
        });
    
        app.listen(process.env.VCAP_APP_PORT || 3000);
    });
    
  2. Use the synchronous version of readFile (which is readFileSync).

    // ...
    content = fs.readFileSync('./config/db.json');
    
    var config = JSON.parse(content);
    // ...
    
Sign up to request clarification or add additional context in comments.

Comments

0

content is equal to undefined when you try to parse it. You should parse your JSON data in the readFile callback or use readFileSync instead.

Also you should probably not throw from a callback.

This leads me to think that you have some misconceptions of how node.js works and I strongly recommend you read this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.