系统性学习Node.js(5)—手写 fs 核心方法( 四 )


实现原理很简单 , 改变 flags 的属性为追加状态即可
const appendFile = (path, data, options, cb) => {
cb = maybeCallback(cb || options)
options = getOptions(options, {
encoding: 'utf8',
mode: 0o666,
flag: 'a'
})
writeFile(path, data, options, cb)
}
最后一个方法 copyFile原生方法的使用方式如下:fs.copyFile('源文件.txt', '目标文件.txt', callback);
代码先不解释了 xdm , 已经快一点了 , 我得先睡了 , 先贴代码 , 有时间再补解释const copyFile = (source, target, cb) => {
cb = maybeCallback(cb)
const BUFFER_LEN = 4
const buf = Buffer.alloc(BUFFER_LEN)
let pos = 0
fs.open(target, 'r', 0o666, (err, rfd) => {
if (err) {
return cb(err)
}
fs.open(source, 'w', 0o666, (err, wfd) => {
if (err) {
return cb(err)
}
const next = () => {
fs.read(rfd, buf, 0, BUFFER_LEN, pos, (err, bytesRead) => {
if (err) {
return cb(err)
}
fs.write(wfd, buf, 0, bytesRead, pos, () => {
console.log('写入')
pos += bytesRead
if (!bytesRead) {
return
}
next()
})
})
}
next()
})
})
}
最后下一期会手写文件流(ReadStream/WriteStream) , 敬请期待 。
如果这篇文章对你有帮助 , 希望点赞鼓励一下笔者~~~