node.js 如何读取json文件内容

最简单的方式:

const config = require('./config.json')
console.log("name",config.name)
console.log("age",config.age)

require方法的缺点:
– 内容会被缓存,不适合动态变更的json文件
– 仅支持后缀为json的文件

稍微复杂的方法:

const fs = require('fs');

try {

    const data = fs.readFileSync('./config.json', 'utf8');

    // parse JSON string to JSON object
    const config = JSON.parse(data);

    console.log("name",config.name)
    console.log("age",config.age)

} catch (err) {
    console.log(`Error reading file from disk: ${err}`);
}

Leave a Reply

Your email address will not be published. Required fields are marked *