Unifx Unifx - 1 month ago 7
Javascript Question

How to do a foreach with delay to perform a search and replace function. WITH DELAY

so here is an array and i want to do a find and replace for each item in the array and search for the key and replace with the value, but this does not work. it searches for strawberries for 5 times.

Also no idea if i would require a delay with something like this?

var path = require('path');
var fs = require('fs');
var cnf = {
apples : 'ill replace this value with this',
pears : 'ill replace this value with this',
bananaas : 'ill replace this value with this',
peaches : 'ill replace this value with this',
strawberries : 'ill replace this value with this'
}

for(var k in cnf) {
fs.readFile(path.resolve('./file-to-search.txt'), 'utf8', function (err,data) {
if (err) return console.log(err)
var searchReplace = data.replace(k, cnf[k])
fs.writeFile(path.resolve('./file-to-search.txt'), searchReplace, 'utf8', function (err) {
if (err) return console.log(err)
});
});
}

Answer

Rather than reading/writing the file on each search and replace, read the file once, perform each of the search and replaces, then write out the final results.

fs.readFile(path.resolve('./file-to-search.txt'), 'utf8', function (err,data) {
  if (err)  return console.log(err);
  for(var k in cnf) {
    data = data.replace(k, cnf[k]);
  }
  fs.writeFile(path.resolve('./file-to-search.txt'), data, 'utf8', function (err) {
    if (err) return console.log(err);
  });
});