本文主要讲述文件基本基本操作,主要适合于看node文档有点吃力的读者。本文尽量保持入门的纯粹简单,循序渐进,一步一步掌握node.js中的文件的操作。
未安装则移步node官网下载安装
包含两个文件fileHandle.js和package.json。
fileHanle.js: 操作文件
package.json: 被操作文件
通过node给定的api同步读取(readFileSync)和同步写入(writeFileSync)完成文件内容修改
/** * 文件处理,以处理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‘})
{ "name": "ming-scripts", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
原文:https://www.cnblogs.com/xingguozhiming/p/12928926.html