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.
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()
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With