Can't parse json with node.js

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

提交回复
热议问题