从零开始Node.js—01文件读写操作

fs是Node.js内置的模块,是file system文件系统的缩写。使用fs接口函数可以轻松读写文件内容

引入fs🤏

两种方法

// commonjs
const fs = require('fs');

//es6
import * as fs from 'fs';

目前以.js结尾文件默认使用es6格式。如果想使用commonjs形式,需要执行npm init,生成package.json配置文件,然后在配置文件中添加一行"type": "commonjs",默认"type": "es6"

读文件📖

// 异步读取
fs.readFile("fileName","utf8",(err,data)=>{
	if(err) throw err.message;
	//处理data,和data有关的所有都写在这里
});

// 同步读取
const data = fs.readFileSync("fileName","utf8");
// 处理data

写文件📝

若文件名之前不存在,会创新一个新的file。如果存在的话,内容会覆盖。如果想要追加内容,增加{flag:"a"},a代表append,默认是w。

fs.writeFile("fileName",data,{flag:"a",encoding:"utf8"},errCallBack)
// 异步写入
fs.writeFile("fileName",data,"utf8",(err)=>{
	if(err) throw err.message;
	console.log("write success!")
});

// 同步写入
fs.writeFileSync("fileName",data,"utf8");

代码小练习🙋

文件read.txt中有字符串如下:

同济=嘉定 上交=闵行 复旦=杨浦 华理=奉贤

要求读取并以如下形式写入write.txt中

同济:嘉定
上交:闵行
复旦:杨浦
华理:奉贤

异步

// 1.引入fs模块
const fs = require('fs');

// 2.读取文件 回调是异步的
fs.readFile(__dirname+'/file/read.txt','utf8' ,(err, data)=>{
  if(err) throw err.message;
  console.log("read success!", data);

  // 3.操纵字符串
  const oldStr = data;
  const newStr = oldStr.replace(/=/g,":").replace(/ /g,"\r\n"); // windows中换行符\r\n

  // 4. 写入文件
  fs.writeFile(__dirname+'/file/write.txt',newStr,'utf8',(err)=>{
    if(err) throw err.message;
    console.log('write success!')
  });

});
  

同步

// 1.引入fs模块
const fs = require('fs');

// 2.读取文件 回调是异步的
const data = fs.readFileSync(__dirname+'/file/read.txt','utf8');

if(!data) throw new Error;
console.log("read success!", data);

// 3.操纵字符串
const oldStr = data;
const newStr = oldStr.replace(/=/g,":").replace(/ /g,"\r\n"); // windows中换行符\r\n

  // 4. 写入文件
fs.writeFileSync(__dirname+'/file/write.txt',newStr,'utf8');

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值