- 1 year ago
How to replace text in file with npm run scripts in package.json Windows OS
To replace text in a file using an npm run script in a Windows OS, you can use Node.js and a custom script within your package.json file. Here's an example of how you can achieve this:
Install the
replace-in-file
package: Open a command prompt or terminal in your project directory and run the following command to install thereplace-in-file
package as a development dependency:bashnpm install replace-in-file --save-dev
Add the script to package.json: In your package.json file, add a new script that executes the custom Node.js script to perform the text replacement. For example:
json"scripts": {
"replace-text": "node replace-text.js"
}
Create the replace-text.js script: Create a JavaScript file (e.g.,
replace-text.js
) in your project directory. This script will use thereplace-in-file
package to perform the text replacement. Here's an example implementation:javascriptconst replace = require('replace-in-file');
const options = {
files: 'path/to/file.txt',
from: /old-text/g,
to: 'new-text',
};
try {
const results = replace.sync(options);
console.log('Replacement results:', results);
} catch (error) {
console.error('Error occurred:', error);
}
Replace
'path/to/file.txt'
with the actual path to your target file,/old-text/g
with the regular expression or text you want to replace, and'new-text'
with the replacement text.Run the script: Execute the script by running the following command in the command prompt or terminal:
bashnpm run replace-text
This will execute the custom script and perform the text replacement in the specified file.
By following these steps, you can use an npm run script with a custom Node.js script to replace text in a file on Windows using the replace-in-file
package. Make sure to adapt the file path and replacement details according to your specific requirements.