Skip to content

Commit 019f5b5

Browse files
committed
refactor: allow replace script to replace in multiple files
1 parent fcea7cd commit 019f5b5

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

scripts/replace.js

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,32 @@
1111
const fs = require('fs');
1212
const path = require('path');
1313

14-
const [search, replace, file] = process.argv.slice(2);
14+
const [search, replace, ...files] = process.argv.slice(2);
1515

16-
if (!search || !replace || !file) {
16+
if (!search || !replace || !files.length) {
1717
// The path of the script relative to the directory where the user ran the
1818
// script to be used in the error message demonstrating the usage.
1919
const scriptPath = path.relative(process.cwd(), __filename);
2020

2121
console.error('Missing arguments.');
22-
console.table({ search, replace, file });
22+
console.table({ search, replace, files });
2323

24-
console.error(`Usage: node ${scriptPath} <search> <replace> <file>`);
24+
console.error(`Usage: node ${scriptPath} <search> <replace> <files...>`);
2525
process.exit(1);
2626
}
2727

28-
try {
29-
const filePath = path.resolve(process.cwd(), file);
28+
for (const file of files) {
29+
try {
30+
const filePath = path.resolve(process.cwd(), file);
3031

31-
const fileContent = fs.readFileSync(filePath, 'utf8');
32+
const fileContent = fs.readFileSync(filePath, 'utf8');
3233

33-
const newContent = fileContent.replaceAll(search, replace);
34+
const newContent = fileContent.replaceAll(search, replace);
3435

35-
fs.writeFileSync(filePath, newContent);
36-
} catch (error) {
37-
console.error('An error occurred while replacing the content of the file.');
38-
console.error(error);
39-
process.exit(1);
36+
fs.writeFileSync(filePath, newContent);
37+
} catch (error) {
38+
console.error(`An error occurred while replacing the content of the file: ${file}.`);
39+
console.error(error);
40+
process.exit(1);
41+
}
4042
}

0 commit comments

Comments
 (0)