在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('----------修改成功-------------');
   }
    
}); 

 

相关文章:

  • 2022-12-23
  • 2021-12-31
  • 2021-07-17
  • 2021-05-29
  • 2021-11-11
猜你喜欢
  • 2021-08-10
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案