Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace does not work on temporary file

I'm using the replace module from NPM successfully (see the first example). However, I want to keep the original file and process a new (temporary) file that is a copy of it. Here is what I tried:

Works:

var replace = require("replace");
replace({
    regex: "foo",
    replacement: "bar",
    paths: [path_in],
    recursive: true,
    silent: true,
});

Doesn't work:

var replace = require("replace");
var fs = require('fs');
fs.createReadStream(path_in).pipe(fs.createWriteStream(path_temp));
replace({
    regex: "foo",
    replacement: "bar",
    paths: [path_temp],
    recursive: true,
    silent: true,
});

Do I need to close the pipe()? Not sure what to do here..

Thanks,

Edit: This GitHub issue is related.

like image 240
jeff Avatar asked May 29 '26 16:05

jeff


1 Answers

The .pipe() is asynchronous so you need to wait for the .pipe() to finish before trying to use the destination file. Since .pipe() returns the destination stream, you can listen for the close or error events to know when it's done:

var replace = require("replace");
var fs = require('fs');
fs.createReadStream(path_in).pipe(fs.createWriteStream(path_temp)).on('close', function() {
    replace({
        regex: "foo",
        replacement: "bar",
        paths: [path_temp],
        recursive: true,
        silent: true,
    });
}).on('error', function(err) {
    // error occurred with the .pipe()
});
like image 79
jfriend00 Avatar answered Jun 01 '26 10:06

jfriend00