Search code examples
node.jsnode.js-stream

How can I rotate the file I'm writing to in node.js?


I'm writing records to a file in node.js and I need to rotate the file with a new one every so many lines or after a duration but I can't lose any lines in the process. If I try with fs.createWriteStream to create a new stream I end up losing lines by overwriting the old stream. Any advise would be much appreciated.


Solution

  • Don't overwrite the old stream. Create the new stream as a separate resource.

    var activestream;
    
    function startup() {
        activestream = fs.createWriteStream('path');
    }
    
    function record(line) {
        activestream.write(line);
    }
    
    function rotate() {
        var newstream = fs.createWriteStream('path2');
        activestream.end();
        activestream = newstream;
    }
    

    ... something like that should work. Obviously you'll have to figure out how to manage the paths.