一个已经存在的文件,里头有内容,但我想从文件开头添加内容,该怎么去添加.
let stream = fs.createReadStream('a.txt') stream.unshift(Buffer.from('添加内容'))
这样行不?
@xiedacon 谢谢,我先试一下
貌似不行的
@zhoujinhai 添加之后还需要写回文件吗?
var path = require('path'); var fs = require('mz/fs'); async function appendFileHeadAsync(filepath, head) { if (!await fs.exists(filepath)) throw new Error("file not exist!!"); var new_file_path = path.format({ root: '/ignored', name: path.parse(filepath).name + "_n", ext: path.parse(filepath).ext }); await fs.writeFile(new_file_path, Buffer.concat([ Buffer.from(head, "utf8"), await fs.readFile(filepath, { "encoding": null }) ]), { "encoding": "utf8", "flag": "w" }); await fs.unlink(filepath); await fs.rename(new_file_path, filepath); return true; } appendFileHeadAsync(path.join(__dirname, 'a/test13333.txt'), "hello node js \r\n").then(a => { console.dir("success"); }).catch(err => { console.dir(err); });
@xiedacon 嗯啊 是的
@godghdai 好的,谢谢!我先看一下
let stream = fs.createReadStream('a.txt') stream.unshift(Buffer.from('添加内容')) stream.pipe(fs.createWriteStream('b.txt'))
@zhoujinhai 这样写回去就行了 godghdai 那个好些,封装成方法了,有验证
@xiedacon 都可以 嘿嘿!谢谢啦
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
这样行不?
@xiedacon 谢谢,我先试一下
貌似不行的
@zhoujinhai 添加之后还需要写回文件吗?
@xiedacon 嗯啊 是的
@godghdai 好的,谢谢!我先看一下
@zhoujinhai 这样写回去就行了 godghdai 那个好些,封装成方法了,有验证
@xiedacon 都可以 嘿嘿!谢谢啦