如何使用node.js附加到特定位置的文件? [英] how to append to a file on particular position using node.js?
本文介绍了如何使用node.js附加到特定位置的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,我想将数据附加到文件上的特定位置.
I have a file and I want to append data to particular position on it.
我经历了 http://nodejs.org/api/fs.html#fs_fs_appendfile_filename_data_options_callback,但我找不到将数据附加到文件中特定位置的方法.
I went through http://nodejs.org/api/fs.html#fs_fs_appendfile_filename_data_options_callback but I couldn't found to append data on specific position in file.
因此,我们将不胜感激.谢谢.!
So any help would be appreciated.Thank you.!!
推荐答案
请参阅此 link
使用此功能,您可以写入文件中的特定位置.
Using this you can write to a specific position in a file.
代码段:
var position = 5;
var file_path = 'file.txt';
var new_text = 'abcde';
fs.readFile(file_path, function read(err, data) {
if (err) {
throw err;
}
var file_content = data.toString();
file_content = file_content.substring(position);
var file = fs.openSync(file_path,'r+');
var bufferedText = new Buffer(new_text+file_content);
fs.writeSync(file, bufferedText, 0, bufferedText.length, position);
fs.close(file);
});
file.txt 应该在同一路径上.
file.txt 已包含以下文本: OldText
输出:新文本将为 OldTe abcde
xt ,即OldTeabcdext
Output: The new text will be OldTeabcde
xt i.e, OldTeabcdext
这篇关于如何使用node.js附加到特定位置的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文