One way to do it is to read each file, parse it, then update what you need to update and then finally write it back to disk again.
Here my test.js script:
import { readFile, writeFile } from "fs/promises";
async function replaceInFiles(){
const replacements = ["Blue Jeans", "Red Jacket", "Hat", "Shirt", "Floral Dress", "Wollen Jacket", "Green belt", "Shoes", "Orange Shirt", "Belt"]
await Promise.all(replacements.map(async (replaceWith, idx) => {
const filename = `${idx + 1}.json`;
// read file
let file;
try {
file = await readFile(filename);
} catch (error) {
console.log(`Failed to read ${filename}. ${error}`)
return;
}
// parse content
const parsed = JSON.parse(file);
// replace description
parsed.description = replaceWith;
// write updated file with intendation of 4
try {
await writeFile(filename, JSON.stringify(parsed, null, 4));
} catch (error) {
console.log(`Failed to write ${filename}. ${error}`)
return;
}
console.log(`Updated ${filename}.`);
}));
console.log("Done.")
}
(async () => {
await replaceInFiles();
})();
I have tested it with to files:
1.json
{ "description": "Example" }
2.json
{ "description": "Example2" }
Then I run the script using node test.js and this result in the following:
Console
Failed to read 3.json. Error: ENOENT: no such file or directory, open '3.json'
Failed to read 4.json. Error: ENOENT: no such file or directory, open '4.json'
Failed to read 5.json. Error: ENOENT: no such file or directory, open '5.json'
Failed to read 6.json. Error: ENOENT: no such file or directory, open '6.json'
Failed to read 7.json. Error: ENOENT: no such file or directory, open '7.json'
Failed to read 9.json. Error: ENOENT: no such file or directory, open '9.json'
Failed to read 8.json. Error: ENOENT: no such file or directory, open '8.json'
Failed to read 10.json. Error: ENOENT: no such file or directory, open '10.json'
Updated 1.json.
Updated 2.json.
Done.
1.json
{
"description": "Blue Jeans"
}
2.json
{
"description": "Red Jacket"
}
Edit
As you've mentioned in the comment you want to read the replacements from a text file here what you need to add to the previous code.
replacements.txt
Blue Jeans
Red Jacket
Hat
Shirt
Floral Dress
Wollen Jacket
Green belt
Shoes
Orange Shirt
Belt
Here the code to populate the replacements array given you have above file with every element being on a new line as you've described in your comment:
const replacementStr = await readFile("replacements.txt", { encoding: "utf8" });
const replacements = replacementStr.split("\n");
// to make the split work for any OS no matter the line endings you can use
const replacements = replacementStr.split(/\r?\n|\r/);