node中的文件操作(读取)

简单读取方式

/*
fs.readFile(path[,options],callback){
path 要读取文件的路径 + 文件名 + 后缀
options: 配置对象
callback 回调
err 错误对象
data 读取出来的数据
}
*/
let fs = require('fs')
fs.readFile(__dirname + '/demo.text',(err,data)=>{
   if(err){
       console.log(err)
  }else{
       console.log(data)
       // 写入其他文件
       fs.writeFile("../haha.text",data,(err)=>{
           if(err) console.log(err)
           else console.log("文件写入成功")
      })
  }
})
  • 简单读写流程
    • 首先将全部文件读到内存中
    • 然后在写入硬盘中
    • 缺点
      • 如果文件过大超过内存容量会产生内存溢出
      • 如果写入超出硬盘最大

流式读取方式

/*
fs.createReadStream(path[,options]){
path 文件路径+文件名+后缀
option
flags
encoding
fd
mode
autoClose
emitclose
start 起始偏移量
end 结束偏移量
highWatermark 每次读取数据的大小,默认值是64*1024
}
*/
let fs = require("fs");
// 创建一个可读流
let rs = fs.createReadStream(__dirname + "/test.mp4/")
// 创建一个可写流
let ws = fs.createWirteStream("../haha.mp4")
// 只要用到了流,就必须监听流的状态
rs.on("open",function(){
   console.log('可读流打开了')
})
rs.on('close',function(){
   console.log('可读流关闭了');
   ws.close() // 当读流完成后,关闭可写流
})
ws.on("open",function(){
   console.log('可写打开了')
})
ws.on('close',function(){
   console.log('可写流关闭了')
})
// 给可读流绑定一个data,就会触发可读流自动读取内容
let result = rs.on("data",function(data){
   // Buffer实例的length属性,是表示该Buffer实例占用内存空间的大小
   console.loga(data.length) // 表示文件的大小
   ws.wrirte(data)
})


暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇