使用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

參考來源

代碼倉庫地址

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM