首页 > 其他 > 详细

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

时间:2020-05-21 11:11:42      阅读:78      评论:0      收藏:0      [点我收藏+]

前言

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

环境

  • node,检测是否安装node

技术分享图片

 

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

 

文件目录

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

fileHanle.js: 操作文件

package.json: 被操作文件

技术分享图片

通过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

技术分享图片

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

技术分享图片

参考来源

代码仓库地址

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!