|
| 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