文件目錄
通過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'})
- 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" }
預期效果
- 在終端找到當前目錄執行node fileHanle.js
- 查看package.json是否完成改變
參考來源
- http://nodejs.cn/api/fs.html#fs_fs_readfilesync_path_options
- http://nodejs.cn/api/fs.html#fs_fs_writefilesync_file_data_options
代碼倉庫地址