系统性学习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) , 敬请期待 。
如果这篇文章对你有帮助 , 希望点赞鼓励一下笔者~~~
- 学习了大数据开发知识,但是面试却屡屡碰壁该怎么办
- 大一上学期学了Python,希望主攻大数据还应该学习什么语言
- 大一下学期转入计算机专业,寒假期间该重点学习什么内容
- 从运维岗转向开发岗,该选择学习Java还是Python
- 想学习编程,该从哪开始
- 当前学习大数据是否都需要学习Java
- 学习|AWS如何为AI工作者赋能?
- 孩子学习没兴趣没动力 不妨试试讯飞智能学习机X2 Pro
- 本科生想从事人工智能岗位,该如何制定学习规划
- 浩林教育:科技赋能让学习有趣且有效