I am using the 'replace-in-file' module for my node.js project. I have written the node module and app.js file below to (1) take form data from a webpage, (2) create a new file from a template, (3) iterate over each key/value pair in the data object, (4) for each key value pair, search the new file for a string matching the key and replace with the key's corresponding value, and (5) return the new file's name to the client.
When the app runs, a new file is created, but the only search and replace reflected in the new file appears to be the last search and replace run by the .forEach() loop.
Why aren't all of my search and replaces showing up in the new document?
Here is the module I wrote called make-docs.js:
var fs = require('fs');
var replace = require('replace-in-file');
var path = require('path');
// function to build agreement file
exports.formBuild = function(data){
var fileName = data.docType + Date.now() + '.html';
var filePath = __dirname + '/documents/' + fileName;
// make a new agreement
fs.createReadStream(data.docType + '.html').pipe(fs.createWriteStream(filePath));
Object.keys(data).forEach(function(key){
var options = {
//Single file
files: filePath,
//Replacement to make (string or regex)
replace: key,
with: data[key].toUpperCase(),
//Specify if empty/invalid file paths are allowed, defaults to false.
//If set to true these paths will fail silently and no error will be thrown.
allowEmptyPaths: false,
};
replace(options)
.then(changedFiles => {
console.log('Modified files:', changedFiles.join(', '));
console.log(options);
})
.catch(error => {
console.error('Error occurred:', error);
});
})
}
var express = require("express");
var fs = require("fs");
var bodyParser = require("body-parser");
var makeDocs = require("./make-docs.js");
var path = require('path');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/documents', express.static(path.join(__dirname, 'documents')));
app.post("/docs", function(req, res) {
console.log(req.body);
res.send(makeDocs.formBuild(req.body));
});
app.listen(8080,function(){
console.log("Node server listening on port 8080");
});
asyncandbluebirdare two such modules. You've used the promises syntax, so you may be more comfortable withbluebird.bluebirdif you want to work with promises. I'll update my answer to include an example on how you would do it with the promise interface and wait for all promises to complete.