1 | # Replace in file
|
2 |
|
3 | [![npm version](https://img.shields.io/npm/v/replace-in-file.svg)](https://www.npmjs.com/package/replace-in-file)
|
4 | [![node dependencies](https://david-dm.org/adamreisnz/replace-in-file.svg)](https://david-dm.org/adamreisnz/replace-in-file)
|
5 | [![build status](https://travis-ci.org/adamreisnz/replace-in-file.svg?branch=master)](https://travis-ci.org/adamreisnz/replace-in-file)
|
6 | [![coverage status](https://coveralls.io/repos/github/adamreisnz/replace-in-file/badge.svg?branch=master)](https://coveralls.io/github/adamreisnz/replace-in-file?branch=master)
|
7 | [![github issues](https://img.shields.io/github/issues/adamreisnz/replace-in-file.svg)](https://github.com/adamreisnz/replace-in-file/issues)
|
8 |
|
9 | A simple utility to quickly replace text in one or more files or globs. Works synchronously or asynchronously with either promises or callbacks. Make a single replacement or multiple replacements at once.
|
10 |
|
11 | # Index
|
12 | - [Installation](#installation)
|
13 | - [Basic usage](#basic-usage)
|
14 | - [Asynchronous replacement with `async`/`await`](#asynchronous-replacement-with-asyncawait)
|
15 | - [Asynchronous replacement with promises](asynchronous-replacement-with-promises)
|
16 | - [Asynchronous replacement with callback](#asynchronous-replacement-with-callback)
|
17 | - [Synchronous replacement](#synchronous-replacement)
|
18 | - [Return value](#return-value)
|
19 | - [Advanced usage](#advanced-usage)
|
20 | - [Replace a single file or glob](#replace-a-single-file-or-glob)
|
21 | - [Replace multiple files or globs](#replace-multiple-files-or-globs)
|
22 | - [Replace first occurrence only](#replace-first-occurrence-only)
|
23 | - [Replace all occurrences](#replace-all-occurrences)
|
24 | - [Multiple values with the same replacement](#multiple-values-with-the-same-replacement)
|
25 | - [Custom regular expressions](#custom-regular-expressions)
|
26 | - [Multiple values with different replacements](#multiple-values-with-different-replacements)
|
27 | - [Using callbacks for `from`](#using-callbacks-for-from)
|
28 | - [Using callbacks for `to`](#using-callbacks-for-to)
|
29 | - [Ignore a single file or glob](#ignore-a-single-file-or-glob)
|
30 | - [Ignore multiple files or globs](#ignore-multiple-files-or-globs)
|
31 | - [Allow empty/invalid paths](#allow-emptyinvalid-paths)
|
32 | - [Disable globs](#disable-globs)
|
33 | - [Specify glob configuration](#glob-configuration)
|
34 | - [Specify character encoding](#specify-character-encoding)
|
35 | - [Dry run](#dry-run)
|
36 | - [CLI usage](#cli-usage)
|
37 | - [Version information](#version-information)
|
38 | - [License](#license)
|
39 |
|
40 | ## Installation
|
41 | ```shell
|
42 | # Using npm, installing to local project
|
43 | npm i --save replace-in-file
|
44 |
|
45 | # Using npm, installing globally for global cli usage
|
46 | npm i -g replace-in-file
|
47 |
|
48 | # Using yarn
|
49 | yarn add replace-in-file
|
50 | ```
|
51 |
|
52 | ## Basic usage
|
53 |
|
54 | ```js
|
55 | //Load the library and specify options
|
56 | const replace = require('replace-in-file');
|
57 | const options = {
|
58 | files: 'path/to/file',
|
59 | from: /foo/g,
|
60 | to: 'bar',
|
61 | };
|
62 | ```
|
63 |
|
64 | ### Asynchronous replacement with `async`/`await`
|
65 |
|
66 | ```js
|
67 | try {
|
68 | const changes = await replace(options)
|
69 | console.log('Modified files:', changes.join(', '));
|
70 | }
|
71 | catch (error) {
|
72 | console.error('Error occurred:', error);
|
73 | }
|
74 | ```
|
75 |
|
76 | ### Asynchronous replacement with promises
|
77 |
|
78 | ```js
|
79 | replace(options)
|
80 | .then(changes => {
|
81 | console.log('Modified files:', changes.join(', '));
|
82 | })
|
83 | .catch(error => {
|
84 | console.error('Error occurred:', error);
|
85 | });
|
86 | ```
|
87 |
|
88 | ### Asynchronous replacement with callback
|
89 |
|
90 | ```js
|
91 | replace(options, (error, changes) => {
|
92 | if (error) {
|
93 | return console.error('Error occurred:', error);
|
94 | }
|
95 | console.log('Modified files:', changes.join(', '));
|
96 | });
|
97 | ```
|
98 |
|
99 | ### Synchronous replacement
|
100 |
|
101 | ```js
|
102 | try {
|
103 | const changes = replace.sync(options);
|
104 | console.log('Modified files:', changes.join(', '));
|
105 | }
|
106 | catch (error) {
|
107 | console.error('Error occurred:', error);
|
108 | }
|
109 | ```
|
110 |
|
111 | ### Return value
|
112 |
|
113 | The return value of the library is an array of file names of files that were modified (e.g.
|
114 | had some of the contents replaced). If no replacements were made, the return array will be empty.
|
115 |
|
116 | ```js
|
117 | const changes = replace.sync({
|
118 | files: 'path/to/files/*.html',
|
119 | from: 'foo',
|
120 | to: 'bar',
|
121 | });
|
122 |
|
123 | console.log(changes);
|
124 |
|
125 | // [
|
126 | // 'path/to/files/file1.html',
|
127 | // 'path/to/files/file3.html',
|
128 | // 'path/to/files/file5.html',
|
129 | // ]
|
130 | ```
|
131 |
|
132 | ## Advanced usage
|
133 |
|
134 | ### Replace a single file or glob
|
135 | ```js
|
136 | const options = {
|
137 | files: 'path/to/file',
|
138 | };
|
139 | ```
|
140 |
|
141 | ### Replace multiple files or globs
|
142 |
|
143 | ```js
|
144 | const options = {
|
145 | files: [
|
146 | 'path/to/file',
|
147 | 'path/to/other/file',
|
148 | 'path/to/files/*.html',
|
149 | 'another/**/*.path',
|
150 | ],
|
151 | };
|
152 | ```
|
153 |
|
154 | ### Replace first occurrence only
|
155 |
|
156 | ```js
|
157 | const options = {
|
158 | from: 'foo',
|
159 | to: 'bar',
|
160 | };
|
161 | ```
|
162 |
|
163 | ### Replace all occurrences
|
164 | Please note that the value specified in the `from` parameter is passed straight to the native [String replace method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace). As such, if you pass a string as the `from` parameter, it will _only replace the first occurrence_.
|
165 |
|
166 | To replace multiple occurrences at once, you must use a regular expression for the `from` parameter with the global flag enabled, e.g. `/foo/g`.
|
167 |
|
168 | ```js
|
169 | const options = {
|
170 | from: /foo/g,
|
171 | to: 'bar',
|
172 | };
|
173 | ```
|
174 |
|
175 | ### Multiple values with the same replacement
|
176 |
|
177 | These will be replaced sequentially.
|
178 |
|
179 | ```js
|
180 | const options = {
|
181 | from: [/foo/g, /baz/g],
|
182 | to: 'bar',
|
183 | };
|
184 | ```
|
185 |
|
186 | ### Multiple values with different replacements
|
187 |
|
188 | These will be replaced sequentially.
|
189 |
|
190 | ```js
|
191 | const options = {
|
192 | from: [/foo/g, /baz/g],
|
193 | to: ['bar', 'bax'],
|
194 | };
|
195 | ```
|
196 |
|
197 | ### Custom regular expressions
|
198 |
|
199 | Use the [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) constructor to create any regular expression.
|
200 |
|
201 | ```js
|
202 | const str = 'foo';
|
203 | const regex = new RegExp('^' + str + 'bar', 'i');
|
204 | const options = {
|
205 | from: regex,
|
206 | to: 'bar',
|
207 | };
|
208 | ```
|
209 |
|
210 | ### Using callbacks for `from`
|
211 | You can also specify a callback that returns a string or a regular expression. The callback receives the name of the file in which the replacement is being performed, thereby allowing the user to tailor the search string. The following example uses a callback to produce a search string dependent on the filename:
|
212 |
|
213 | ```js
|
214 | const options = {
|
215 | files: 'path/to/file',
|
216 | from: (file) => new RegExp(file, 'g'),
|
217 | to: 'bar',
|
218 | };
|
219 | ```
|
220 |
|
221 | ### Using callbacks for `to`
|
222 | As the `to` parameter is passed to the native [String replace method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace), you can also specify a callback. The following example uses a callback to convert matching strings to lowercase:
|
223 |
|
224 | ```js
|
225 | const options = {
|
226 | files: 'path/to/file',
|
227 | from: /SomePattern[A-Za-z-]+/g,
|
228 | to: (match) => match.toLowerCase(),
|
229 | };
|
230 | ```
|
231 |
|
232 | This callback provides for an extra argument above the String replace method, which is the name of the file in which the replacement is being performed. The following example replaces the matched string with the filename:
|
233 |
|
234 | ```js
|
235 | const options = {
|
236 | files: 'path/to/file',
|
237 | from: /SomePattern[A-Za-z-]+/g,
|
238 | to: (...args) => args.pop(),
|
239 | };
|
240 | ```
|
241 |
|
242 | ### Ignore a single file or glob
|
243 |
|
244 | ```js
|
245 | const options = {
|
246 | ignore: 'path/to/ignored/file',
|
247 | };
|
248 | ```
|
249 |
|
250 | ### Ignore multiple files or globs
|
251 |
|
252 | ```js
|
253 | const options = {
|
254 | ignore: [
|
255 | 'path/to/ignored/file',
|
256 | 'path/to/other/ignored_file',
|
257 | 'path/to/ignored_files/*.html',
|
258 | 'another/**/*.ignore',
|
259 | ],
|
260 | };
|
261 | ```
|
262 |
|
263 | Please note that there is an [open issue with Glob](https://github.com/isaacs/node-glob/issues/309) that causes ignored patterns to be ignored when using a `./` prefix in your files glob. To work around this, simply remove the prefix, e.g. use `**/*` instead of `./**/*`.
|
264 |
|
265 | ### Allow empty/invalid paths
|
266 | If set to true, empty or invalid paths will fail silently and no error will be thrown. For asynchronous replacement only. Defaults to `false`.
|
267 |
|
268 | ```js
|
269 | const options = {
|
270 | allowEmptyPaths: true,
|
271 | };
|
272 | ```
|
273 |
|
274 | ### Disable globs
|
275 | You can disable globs if needed using this flag. Use this when you run into issues with file paths like files like `//SERVER/share/file.txt`. Defaults to `false`.
|
276 |
|
277 | ```js
|
278 | const options = {
|
279 | disableGlobs: true,
|
280 | };
|
281 | ```
|
282 |
|
283 | ### Specify glob configuration
|
284 | Specify configuration passed to the `glob` call:
|
285 |
|
286 | ```js
|
287 | const options = {
|
288 | glob: {
|
289 | //Glob settings here
|
290 | },
|
291 | };
|
292 | ```
|
293 |
|
294 | Please note that the setting `nodir` will always be passed as `false`.
|
295 |
|
296 | ### Specify character encoding
|
297 | Use a different character encoding for reading/writing files. Defaults to `utf-8`.
|
298 |
|
299 | ```js
|
300 | const options = {
|
301 | encoding: 'utf8',
|
302 | };
|
303 | ```
|
304 |
|
305 | ### Dry run
|
306 | To do a dry run without actually making replacements, for testing purposes. Defaults to `false`.
|
307 |
|
308 | ```js
|
309 | const options = {
|
310 | dry: true,
|
311 | };
|
312 | ```
|
313 |
|
314 | ## CLI usage
|
315 |
|
316 | ```sh
|
317 | replace-in-file from to some/file.js,some/**/glob.js
|
318 | [--configFile=replace-config.js]
|
319 | [--ignore=ignore/files.js,ignore/**/glob.js]
|
320 | [--encoding=utf-8]
|
321 | [--disableGlobs]
|
322 | [--isRegex]
|
323 | [--verbose]
|
324 | [--dry]
|
325 | ```
|
326 |
|
327 | Multiple files or globs can be replaced by providing a comma separated list.
|
328 |
|
329 | The flags `--disableGlobs`, `--ignore` and `--encoding` are supported in the CLI.
|
330 |
|
331 | The setting `allowEmptyPaths` is not supported in the CLI as the replacement is
|
332 | synchronous, and this setting is only relevant for asynchronous replacement.
|
333 |
|
334 | To list the changed files, use the `--verbose` flag. To do a dry run, use `--dry`.
|
335 |
|
336 | A regular expression may be used for the `from` parameter by specifying the `--isRegex` flag.
|
337 |
|
338 | The `from` and `to` parameters, as well as the files list, can be omitted if you provide this
|
339 | information in a configuration file. You can provide a path to a configuration file
|
340 | (either Javascript or JSON) with the `--configFile` flag. This path will be resolved using
|
341 | Node’s built in `path.resolve()`, so you can pass in an absolute or relative path.
|
342 |
|
343 | ## Version information
|
344 | From version 3.0.0 onwards, replace in file requires Node 6 or higher. If you need support for Node 4 or 5, please use version 2.x.x.
|
345 |
|
346 | ## License
|
347 | (MIT License)
|
348 |
|
349 | Copyright 2015-2018, [Adam Reis](https://adam.reis.nz), co-founder at [Hello Club](https://helloclub.com/?source=npm)
|