nodejs读写json配置文件

在nodejs项目中有时会用到读取配置文件,以下是简单的读写配置文件的例子,配置文件为json格式。

json格式的配置文件内容如下:

config.json

{"name":"小三","age":"18"}

 

js程序demo如下:

jsontest.js

var fs = require('fs');

//读取配置文件,变量config的类型是Object类型
var config = require('./config');

//修改配置文件
config["name"] = "小四";
console.log(config);
//将修改后的配置写入文件前需要先转成json字符串格式
var jsonstr = JSON.stringify(config);

//将修改后的内容写入文件
fs.writeFile('./config.json', jsonstr, function(err) {
   if (err) {
      console.error(err);
   }else{
       console.log('----------修改成功-------------');
   }
    
}); 

 

posted @ 2019-12-02 11:00  _DC  阅读(12928)  评论(2编辑  收藏  举报