Can't parse json with node.js

后端 未结 2 1130
庸人自扰
庸人自扰 2021-01-29 10:47

I am a node.js beginner and I am trying to read a json file, but when I\'m running \'npm start\' in the terminal I get this error:

undefined:3462

SyntaxError: U         


        
相关标签:
2条回答
  • 2021-01-29 11:30

    readFile is the asynchronous version. You should either just use readFileSync, or rewrite it to be properly asynchronous.

    console.log('analoc request');
    
    var fs = require('fs');
    
     fs.readFile('./files/sample_data.json', function(err,config){
    console.log('Config: ' + JSON.parse(config));
    });
    

    Or:

    var config = fs.readFileSync('./files/sample_data.json');
    console.log('Config: ' + JSON.parse(config));
    
    0 讨论(0)
  • 2021-01-29 11:39

    readFile doesn't have a return value. You are trying to parse "undefined" as if it were JSON. The file is passed to the callback function after it has been read.

    fs.readFile('./files/sample_data.json', function (err, data) {
        if (err) throw err;
        var config = JSON.parse(data);
        console.log('Config: ', config);
    });
    
    0 讨论(0)
提交回复
热议问题