Replacement doesn't work in temp file

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

Works:

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

      

Does not 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 pipe()

? Not sure what to do here.

Thank,

Edit: This GitHub issue is linked.

+3


source to share


1 answer


.pipe()

is asynchronous, so you need to wait for completion .pipe()

before trying to use the target file. Since the .pipe()

target stream returns, you can listen for events close

or error

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()
});

      

+1


source







All Articles