node给java发送文件_如何在Node中附加文件?

我正在尝试将字符串追加到日志文件。 但是writeFile每次写入字符串之前都会擦除内容。

fs.writeFile('log.txt', 'Hello Node', function (err) {

if (err) throw err;

console.log('It\'s saved!');

}); // => message.txt erased, contains only 'Hello Node'

任何想法如何以简单的方式做到这一点?

#1楼

对于偶尔的追加,您可以使用appendFile ,每次调用它时都会创建一个新的文件句柄:

const fs = require('fs');

fs.appendFile('message.txt', 'data to append', function (err) {

if (err) throw err;

console.log('Saved!');

});

const fs = require('fs');

fs.appendFileSync('message.txt', 'data to append');

但是,如果您重复追加到同一文件,最好重用文件handle 。

#2楼

fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')

fs.writeSync(fd, 'contents to append')

fs.closeSync(fd)

#3楼

Node.js 0.8具有fs.appendFile :

fs.appendFile('message.txt', 'data to append', (err) => {

if (err) throw err;

console.log('The "data to append" was appended to file!');

});

#4楼

这是完整的脚本。 填写文件名并运行它,它应该可以工作! 这是有关脚本背后逻辑的视频教程 。

var fs = require('fs');

function ReadAppend(file, appendFile){

fs.readFile(appendFile, function (err, data) {

if (err) throw err;

console.log('File was read');

fs.appendFile(file, data, function (err) {

if (err) throw err;

console.log('The "data to append" was appended to file!');

});

});

}

// edit this with your file names

file = 'name_of_main_file.csv';

appendFile = 'name_of_second_file_to_combine.csv';

ReadAppend(file, appendFile);

#5楼

您需要打开它,然后写它。

var fs = require('fs'), str = 'string to append to file';

fs.open('filepath', 'a', 666, function( e, id ) {

fs.write( id, 'string to append to file', null, 'utf8', function(){

fs.close(id, function(){

console.log('file closed');

});

});

});

这里有一些链接将有助于解释参数

编辑 :此答案不再有效,请查看新的fs.appendFile方法进行追加。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值