node下使用buffer
// 使用buffer分段完整读写复制文件
let buf = Buffer.alloc(10)
let bufSize = buf.length
let offsetIndex = 0
fs.open(path.join(__dirname,'a.txt'), 'r', (err, rfd) => {
fs.open(path.resolve('b.txt'), 'w',(err, wfd) => {
function next( ) {
fs.read(rfd, buf, 0, bufSize, offsetIndex, (err,readBytes) => {
if(!readBytes){ //说明内容为空
fs.close(rfd, () => {
fs.close(wfd, () => { })
})
return
}
offsetIndex += readBytes
fs.write(wfd, buf, 0, readBytes, (err,bytesWritten) => {
next()
})
})
}
next()
})
})
// 给buffer原型添加自定义split方法
Buffer.prototype.splitt = function(seq) {
let len = Buffer.from(seq).length // 对传入字符进行长度解析
let resArr = []
let start = 0
while(this.indexOf(seq, start) !== -1) {
let end = this.indexOf(seq, start)
resArr.push( this.slice(start, end).toString() )
start = end + len
// 此处len不能使用seq.length是因为非英文字符在buffer所占字节不一定是1,比如中文一个字符占3字节
}
resArr.push(this.slice(start).toString()) //如果需要得到原始Buffer数据,去掉toString即可
return resArr
}
let cc77= Buffer.from('吃饭,睡觉,打豆豆')
let cc55 = cc77.splitt(',')
console.log("🚀 ~ file: app.js:40 ~ cc55", cc55) // [ '吃饭', '睡觉', '打豆豆' ]