如何在不创建新文件的情况下继续在fs中写入文件?

时间:2018-07-04 13:26:03

标签: javascript node.js discord.js

帮助我一直保持记录文件,直到我告诉Discord机器人wfileStream.end();如何解决此问题,不起作用会引发错误,这是我做错了。。

我正在用它来写文件

const fs = require('fs');

代码

if (msg.content === 'cmdrecordvoice' && msg.guild.voiceConnection !== null) {
    var voice_receiver = msg.guild.voiceConnection.createReceiver();
    var wfileStream = fs.createWriteStream('record.opus');
    msg.guild.voiceConnection.on('speaking', (user, speaking) => {
        if (speaking) {
            console.log('recording voice!');
            const audioStream = voice_receiver.createOpusStream(user);
            audioStream.pipe(wfileStream);
            audioStream.on('end', () => {
            console.log('end of recording voice!');

            });
        }
    });
}

我知道我必须将文件创建为全局变量wfileStream,否则我应该使用fs。“ code”从机器人在文件写入时留下的位置开始重写

1 个答案:

答案 0 :(得分:0)

只需手动创建一个名称为record.opus的文件。然后,您只需将数据追加到该文件即可。

if (msg.content === 'cmdrecordvoice' && msg.guild.voiceConnection !== null) {
    var voice_receiver = msg.guild.voiceConnection.createReceiver();
    msg.guild.voiceConnection.on('speaking', (user, speaking) => {
        if (speaking) {
            var wfileStream = fs.createWriteStream('record.opus', {'flags': 'a'}); // creating a write able stream when 'speaking'
            // use {'flags': 'a'} to append and {'flags': 'w'} to erase and write a new file
            console.log('recording voice!');
            const audioStream = voice_receiver.createOpusStream(user);
            audioStream.pipe(wfileStream);
            audioStream.on('end', () => {
               console.log('end of recording voice!');
               wfileStream.end(); // close stream
            });
        }
    });
}