Read json file content with require vs fs.readFile

前端 未结 7 1974
说谎
说谎 2020-11-30 03:46

Suppose that for every response from an API, i need to map the value from the response to an existing json file in my web application and display the value from the json. Wh

相关标签:
7条回答
  • 2020-11-30 04:25

    If your file is empty, require will break. It will throw an error:

    SyntaxError ... Unexpected end of JSON input.

    With readFileSync/readFile you can deal with this:

    let routesJson = JSON.parse(fs.readFileSync('./routes.json', 'UTF8') || '{}');
    

    or:

    let routesJson
    fs.readFile('./dueNfe_routes.json', 'UTF8', (err, data) => {
        routesJson = JSON.parse(data || '{}');
    });
    
    0 讨论(0)
提交回复
热议问题