1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| const fs = require('fs'); const path = require('path');
const BUFFER_SIZE = 10;
const readPath = path.resolve(__dirname, '1.txt'); const writePath = path.resolve(__dirname, '2.txt'); fs.open(readPath, 'r', (err, rfd) => { if (err) { console.error(err) } else { console.log("打开文件fd:" + rfd) fs.open(writePath, 'w', (err, wfd) => { if (err) { console.error(err); } else { console.log("打开文件fd:" + wfd) let readPosition = 0; function next() { let buffer = Buffer.alloc(BUFFER_SIZE); fs.read(rfd, buffer, 0, BUFFER_SIZE, readPosition, (err, bytesRead) => { if (err) { console.error(err); } else { readPosition += bytesRead; if (bytesRead != 0) { fs.write(wfd, buffer, 0, bytesRead, (err, bytesWritten, buffer) => { if (err) { console.error(err); } else { next(); } }) } else { fs.close(rfd, () => { console.log("关闭文件fd:" + rfd) }); fs.close(wfd, () => { console.log("关闭文件fd:" + wfd) }); }
} }) } next() } }) } })
|