亲们,问一下 如何给文件的开头添加内容? - CNode技术社区

亲们,问一下 如何给文件的开头添加内容?
发布于 8 年前 作者 zhoujinhai 5047 次浏览 来自 问答

一个已经存在的文件,里头有内容,但我想从文件开头添加内容,该怎么去添加.

9 回复
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 都可以 嘿嘿!谢谢啦

回到顶部

AltStyle によって変換されたページ (->オリジナル) /