使用node进行文件操作(一):编辑json文件

 文件目录

image.png

通过node给定的api同步读取(readFileSync)和同步写入(writeFileSync)完成文件内容修改

文件代码

  • fileHandle.js
/**
 * 文件处理,以处理package.json文件为例
 */
const fs=require('fs');
/**
 *  修改版本号
 *  @params   
 *   key: 依赖包,例如 "axios"
 *   value: 依赖包版本,例如 "^0.18.0"
 *   filepath: package.json文件路径
 *   type: dependencies(不传默认)或者devDependencies
 */ 
const editDependencies=function({key,value,filepath,type}){
    // 读取文件
    const currFile=fs.readFileSync(filepath);
    console.log('读取成功!')
    const currFileObj=JSON.parse(currFile);
    
    const currType=type || 'dependencies';
    if(currFileObj[currType]) currFileObj[currType][key]=value;
    else currFileObj[currType]={}
    // 写入文件
    fs.writeFileSync(filepath,JSON.stringify(currFileObj));
    console.log('写入成功!')
}
editDependencies({key:"axios",value:"^0.18.0",filepath:'./package.json'})
View Code
  • package.json
{
    "name": "ming-scripts",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
}
View Code

预期效果

  • 在终端找到当前目录执行node fileHanle.js

image.png

  • 查看package.json是否完成改变

image.png

参考来源

代码仓库地址

 

原文地址:https://www.cnblogs.com/xingguozhiming/p/12928926.html