使用node进行文件操作(一)

前言

本文主要讲述文件基本基本操作,主要适合于看node文档有点吃力的读者。本文尽量保持入门的纯粹简单,循序渐进,一步一步掌握node.js中的文件的操作。

环境

  • node,检测是否安装node

image.png

 

未安装则移步node官网下载安装

 

文件目录

包含两个文件fileHandle.js和package.json。

fileHanle.js: 操作文件

package.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
扫描二维码关注公众号,回复: 11236983 查看本文章
  • 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

参考来源

代码仓库地址

 

猜你喜欢

转载自www.cnblogs.com/xingguozhiming/p/12928926.html