1. fs写文件
1.1 普通写入
const fs = require ( 'fs' )
fs. writeFile ( './hello.txt' , '刚刚我错过的大雨' , err => { console. log ( err) ;
} )
fs. writeFileSync ( './text.txt' , 'hello boy!' )
1.2 文件的追加写入
const fs = require ( 'fs' )
fs. appendFile ( './text.txt' , '\r\r\r\r那些年胡夏' , err => { console. log ( err) ;
} )
fs. appendFileSync ( './hello.txt' , 'sometimes!!!' )
1.3 流式写入
const fs = require ( 'fs' )
const ws = fs. createWriteStream ( './诗.txt' ) ws. write ( '曲项向天歌\r' )
ws. write ( '曲项向天歌\r' )
ws. write ( '曲项向天歌\r' )
ws. write ( '曲项向天歌\r' ) ws. end ( )
2. 文件读取
2.1 普通读取
const fs = require ( 'fs' ) fs. readFile ( '../A音频.mp3' , ( err, data ) => { console. log ( err) ; console. log ( data) ;
} ) let data = fs. readFileSync ( './hello.txt' )
console. log ( data. toString ( ) ) ;
2.2 流式读取
const fs = require ( 'fs' )
const rs = fs. createReadStream ( '../资料/测试.xlsx' ) rs. on ( 'data' , chunk => { console. log ( chunk. length) ;
} )
rs. on ( 'end' , ( ) => { console. log ( '读取完成~' ) ;
} )
3. 复制/重命名/移动/删除文件
3.1 复制
const fs = require ( 'fs' )
const process = require ( 'process' )
let data = fs. readFileSync ( '../资料/测试.xlsx' ) fs. writeFileSync ( '../资料/测试2.xlsx' , data)
console. log ( process. memoryUsage ( ) ) ;
const rs = fs. createReadStream ( '../资料/测试.xlsx' )
const ws = fs. createWriteStream ( '../资料/测试4.xlsx' )
rs. pipe ( ws)
3.2 重命名及移动
const fs = require ( 'fs' )
fs. rename ( './古诗.txt' , '../资料/古诗词.txt' , err => { if ( err) { console. log ( '删除失败' ) ; return } console. log ( '删除成功' ) ;
} )
3.3 文件删除
const fs = require ( 'fs' )
fs. rm ( './text.txt' , err => {
} )
4.文件夹相关操作
const fs = require ( 'fs' )
fs. rm ( './a' , { recursive : true } , err => { } )
5.查看文件状态 以及 文件路径
5.1 查看文件状态
const fs = require ( 'fs' ) fs. stat ( '../资料/测试.xlsx' , ( err, data ) => { console. log ( data) ; console. log ( data. isFile ( ) ) ; console. log ( data. isDirectory ( ) ) ;
} )
5.2 文件路径
const fs = require ( 'fs' )
fs. writeFileSync ( 'index.ts' , 'love' )