In a directory there are multiple files with different extensions. I have to find and select .txt files and from these all .txt files there are some words I have to replace with new words.
say , 4 files from my directory are :
File1.txt
File2.txt
File3.txt
File4.txt
now I have to replace word 'mobile' to 'laptop' from all .txt files
than again I have to replace word 'School' to 'College' from all txt.files
and again replace word 'banana' to 'Mango' from all txt.files
and then save the file.
const path = require('path')
const fs = require('fs')
const dirpath = path.join(__dirname, '/')
fs.readdir(dirpath, function(err, files) {
const Files = files.filter(el => path.extname(el) === '.txt')
for (let i=0; i < Files.length; i++) {
console.log(Files[i])
var fs = require('fs')
fs.readFile(Files[i], 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var result = data.replace(/mobile/g, 'laptop');
fs.writeFile(Files[i], result, 'utf8', function (err) {
if (err) return console.log(err);
});
var result2 = data.replace(/School/g, 'College');
fs.writeFile(Files[i], result2, 'utf8', function (err) {
if (err) return console.log(err);
});
});
}
When I run this program only 2nd replace part is working,what should I do!