const { log } = require("console"); const fs = require("fs"); const path = require("path"); const filename = path.resolve(__dirname, "./myfiles1.txt"); // console.log(filename) // fs.readFile(filename,(err,content)=>{ // console.log( 'read', content.toString('utf-8')) // }) // fs.writeFile(filename,'fsfsdfs',(err,content)=>{ // console.log('dsfsd',content) // }) // (async () => { // const result = await fs.promises.stat(filename); // console.log(result); // })(); class File { constructor(filename, name, ext, isFile, size, createTime, updateTime) { this.filename = filename; this.name = name; this.isFile = isFile; this.size = size; this.createTime = createTime; this.updateTime = updateTime; this.ext = ext; } async getContent(isBuffer = false) { if (this.isFile) { if (isBuffer) { return await fs.promises.readFile(this.filename); } else { return await fs.promises.readFile(this.filename, "utf-8"); } } return null; } async getChildren() { if (this.isFile) return []; let children = await fs.promises.readdir(this.filename); console.log(children); children = children.map((name) => { const result = path.resolve(this.filename, name); console.log(result); return File.getFile(result); }); return Promise.all(children); } static async getFile(filename) { const stat = await fs.promises.stat(filename); const name = path.basename(filename); const extName = path.extname(filename); const isFile = stat.isFile(); const size = stat.size; const createTime = new Date(stat.birthtime); const updateTime = new Date(stat.mtime); return new File( filename, name, extName, isFile, size, createTime, updateTime ); } } async function readdir(dirname){ const dirFile = await File.getFile(dirname) return dirFile.getChildren() } async function test() { // const filename = path.resolve(__dirname, "./myfiles/1.txt"); // const file = await File.getFile(filename); // console.log(await file.getContent()); const filename = await path.resolve(__dirname, "./myfiles"); console.log(await readdir(filename)) } test(); return const file = path.resolve(__dirname,'./myfiles/1.txt') //f返回readStream const rs = fs.createReadStream(file,{ encoding:null, highWaterMark:1 , //每次读取数量 如果encoding有值 那么每次读一个字符 如果没有值 那么每次读一个字节 autoClose:true //读完自动关闭 默认为true }) rs.on('open',()=>{ log('文件被打开了') }) rs.on('error',(e)=>{ log('出错了',e.message) }) rs.on('close',()=>{ log('文件关闭') }) // rs.close() //只有注册了这个事件 才会开始读 rs.on('data',(chunk)=>{ // log('读到了一部分',chunk) rs.pause() }) rs.on('end',()=>{ log('结束') }) rs.on('pause',()=>{ log('暂停') setTimeout(() => { rs.resume() }, 10); }) rs.on('resume',()=>{ log('恢复') }) // rs.pause() //暂停读取 出发pause事件 // rs.resume() //恢复读取 触发resume事件View Code
标签:文件,fs,const,log,nodeJS,rs,filename,操作,await From: https://www.cnblogs.com/liagon/p/18209548