const fs = require("fs"); const path = require("path"); // 方法1 直接使用原生的来 (async () => { console.time('方式1') const fileName = path.resolve(__dirname, './fsModule/复制文件1.docx'); const fileCont = await fs.promises.readFile(path.resolve(__dirname, './fsModule/100MB大文件.docx'), 'utf-8'); await fs.promises.writeFile(fileName, fileCont, {encoding: 'utf-8', flag: 'w'}); console.timeEnd('方式1') //方式1: 1318.309ms })() // 方法2 通过流的方法来读取 (() => { console.time('用流的方式读取文件') const fromFileName = path.resolve(__dirname, './fsModule/100MB大文件.docx'); const toFileName = path.resolve(__dirname, './fsModule/复制文件2.docx'); const rs = fs.createReadStream(fromFileName, { autoClose: true, encoding: 'utf-8', highWaterMark: 64 * 1024 * 1024, flags: 'r' }) const ws = fs.createWriteStream(toFileName, { encoding: 'utf-8', flags: 'a', highWaterMark: 16 * 1024 * 1024, autoClose: true }) rs.on('data', chunk => { ws.write(chunk, 'utf-8'); }) rs.on('end', () => { console.log('文件写入完毕!!') }) console.timeEnd('用流的方式读取文件') //用流的方式读取文件: 4.218ms })() // 方式3 优化用流读取 解决背压问题 (() => { console.time('优化用流的方式读取文件') const fromFileName = path.resolve(__dirname, './fsModule/100MB大文件.docx'); const toFileName = path.resolve(__dirname, './fsModule/复制文件3.docx'); const rs = fs.createReadStream(fromFileName, { autoClose: true, encoding: 'utf-8', highWaterMark: 64 * 1024 * 1024, flags: 'r' }) const ws = fs.createWriteStream(toFileName, { encoding: 'utf-8', flags: 'a', highWaterMark: 16 * 1024 * 1024, autoClose: true }) rs.on('data', chunk => { const wsFlag = ws.write(chunk, 'utf-8'); if (!wsFlag) { rs.pause(); } }) ws.on('drain', () => { // 继续读取 rs.resume(); }) rs.on('end', () => { console.log('文件写入完毕!!') ws.end(); }) console.timeEnd('优化用流的方式读取文件') //用流的方式读取文件: 3.006ms })() // 方法四: pipe (() => { console.time('优化用流的方式读取文件') const fromFileName = path.resolve(__dirname, './fsModule/100MB大文件.docx'); const toFileName = path.resolve(__dirname, './fsModule/复制文件4.docx'); const rs = fs.createReadStream(fromFileName, { autoClose: true, encoding: 'utf-8', highWaterMark: 64 * 1024 * 1024, flags: 'r' }) const ws = fs.createWriteStream(toFileName, { encoding: 'utf-8', flags: 'a', highWaterMark: 16 * 1024 * 1024, autoClose: true }) // 直接解决背压问题 rs.pipe(ws); console.timeEnd('优化用流的方式读取文件') // 7.967ms })() // 方法五 copyFile const fromFileName = path.resolve(__dirname, './fsModule/100MB大文件.docx'); const toFileName = path.resolve(__dirname, './fsModule/复制文件5.docx'); fs.copyFile(fromFileName, toFileName,0, ()=>{ console.log('复制完成') })