Node.js之文件复制

1.方式一:readFile

javascript 复制代码
// 导入fs模块
const fs = require("fs")
// 导入process模块
const process = require("process")

// 读取文件内容
let data = fs.writeFileSync('./test.txt')
// 写入文件内容
fs.writeFileSync('./test1.txt', data)

2.方式二:流式操作

javascript 复制代码
// 创建读取流对象
const rs = fs.createReadSteam(./test.txt')
// 创建写入流对象
const ws = fs.createReadSteam(./test2.txt')

3.绑定data事件

javascript 复制代码
// 绑定data事件
rs.on('data', chunk => {
ws.write(chunk)
})

4.查看占用内存,流式占用内存低

javascript 复制代码
// 创建读取流对象
const rs = fs.createReadSteam('./test.txt')
// 创建写入流对象
const ws = fs.createWriteSteam('./test1.txt')
// 绑定data事件
rs.on('data', chunk => {
    ws.write(chunk)
})
rs.on('end', () => {
    console.log(process.memoryUsage())
})
相关推荐
RoyLin6 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
RoyLin11 小时前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
前端双越老师15 小时前
2025 年还有前端不会 Nodejs ?
node.js·agent·全栈
人工智能训练师1 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 天前
pnpm相对于npm,yarn的优势
前端·npm·node.js
huangql5201 天前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
荣达1 天前
koa洋葱模型理解
前端·后端·node.js
csdn_aspnet1 天前
Windows Node.js 安装及环境配置详细教程
windows·node.js
风若飞2 天前
npm ERR! code CERT_HAS_EXPIRED
前端·npm·node.js
csdn_aspnet2 天前
Windows、Linux 系统 nodejs 和 npm 版本更新及错误修复
linux·windows·npm·node.js