Can't parse json with node.js

后端 未结 2 1169
庸人自扰
庸人自扰 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: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);
    });
    

提交回复
热议问题