Skip to content

Commit fcea7cd

Browse files
committed
chore: create a replace script as a replacement for sed
1 parent 70e349c commit fcea7cd

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

.eslintrc.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@ module.exports = {
1212
'jest/globals': true,
1313
},
1414
},
15+
{
16+
// Node Scripts Overrides
17+
files: ['scripts/**'],
18+
env: {
19+
node: true,
20+
},
21+
},
1522
{
1623
// Detox Overrides
1724
files: ['examples/default/e2e/**.js'],

scripts/replace.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* A script to replace all occurrences of a string in a file, this is built as a
3+
* replacement for the `sed` command to make it easier to replace strings with
4+
* special characters without the hassle of escaping them, this is important
5+
* when we are replacing strings that aren't known in advance like parameters
6+
* from files.
7+
*
8+
* Usage: node replace.js <search> <replace> <file>
9+
*/
10+
11+
const fs = require('fs');
12+
const path = require('path');
13+
14+
const [search, replace, file] = process.argv.slice(2);
15+
16+
if (!search || !replace || !file) {
17+
// The path of the script relative to the directory where the user ran the
18+
// script to be used in the error message demonstrating the usage.
19+
const scriptPath = path.relative(process.cwd(), __filename);
20+
21+
console.error('Missing arguments.');
22+
console.table({ search, replace, file });
23+
24+
console.error(`Usage: node ${scriptPath} <search> <replace> <file>`);
25+
process.exit(1);
26+
}
27+
28+
try {
29+
const filePath = path.resolve(process.cwd(), file);
30+
31+
const fileContent = fs.readFileSync(filePath, 'utf8');
32+
33+
const newContent = fileContent.replaceAll(search, replace);
34+
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);
40+
}

0 commit comments

Comments
 (0)