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!
CodePudding user response:
By doing
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);
});
you're
- first, saving the first replaced text to the file
- then, replacing the original text with the second string, and saving that to the file
Not sure what you were trying to achieve with that first write - if you really wanted two writeFile
s, you'd need to wait for the first to finish, and then call readFile
again to get the new content, and then call .replace
on that content. But why not just ditch that first writeFile
entirely and use the string you already have a reference to? (Don't replace data
, the original string, but result
, the result of the first replacement - or, don't create an intermediate variable at all)
fs.readFile(Files[i], 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
const result = data
.replace(/mobile/g, 'laptop')
.replace(/School/g, 'College');
fs.writeFile(Files[i], result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
If you wanted to have an indicator when all files have been replaced, use the fs.promises
API and Promise.all
instead of the callback-based API.