UNPKG

12.1 kBMarkdownView Raw
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
9A 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 - [Counting matches and replacements](#counting-matches-and-replacements)
20- [Advanced usage](#advanced-usage)
21 - [Replace a single file or glob](#replace-a-single-file-or-glob)
22 - [Replace multiple files or globs](#replace-multiple-files-or-globs)
23 - [Replace first occurrence only](#replace-first-occurrence-only)
24 - [Replace all occurrences](#replace-all-occurrences)
25 - [Multiple values with the same replacement](#multiple-values-with-the-same-replacement)
26 - [Custom regular expressions](#custom-regular-expressions)
27 - [Multiple values with different replacements](#multiple-values-with-different-replacements)
28 - [Using callbacks for `from`](#using-callbacks-for-from)
29 - [Using callbacks for `to`](#using-callbacks-for-to)
30 - [Ignore a single file or glob](#ignore-a-single-file-or-glob)
31 - [Ignore multiple files or globs](#ignore-multiple-files-or-globs)
32 - [Allow empty/invalid paths](#allow-emptyinvalid-paths)
33 - [Disable globs](#disable-globs)
34 - [Specify glob configuration](#specify-glob-configuration)
35 - [Making replacements on network drives](#making-replacements-on-network-drives)
36 - [Specify character encoding](#specify-character-encoding)
37 - [Dry run](#dry-run)
38- [CLI usage](#cli-usage)
39- [Version information](#version-information)
40- [License](#license)
41
42## Installation
43```shell
44# Using npm, installing to local project
45npm i --save replace-in-file
46
47# Using npm, installing globally for global cli usage
48npm i -g replace-in-file
49
50# Using yarn
51yarn add replace-in-file
52```
53
54## Basic usage
55
56```js
57//Load the library and specify options
58const replace = require('replace-in-file');
59const options = {
60 files: 'path/to/file',
61 from: /foo/g,
62 to: 'bar',
63};
64```
65
66### Asynchronous replacement with `async`/`await`
67
68```js
69try {
70 const results = await replace(options)
71 console.log('Replacement results:', results);
72}
73catch (error) {
74 console.error('Error occurred:', error);
75}
76```
77
78### Asynchronous replacement with promises
79
80```js
81replace(options)
82 .then(results => {
83 console.log('Replacement results:', results);
84 })
85 .catch(error => {
86 console.error('Error occurred:', error);
87 });
88```
89
90### Asynchronous replacement with callback
91
92```js
93replace(options, (error, results) => {
94 if (error) {
95 return console.error('Error occurred:', error);
96 }
97 console.log('Replacement results:', results);
98});
99```
100
101### Synchronous replacement
102
103```js
104try {
105 const results = replace.sync(options);
106 console.log('Replacement results:', results);
107}
108catch (error) {
109 console.error('Error occurred:', error);
110}
111```
112
113### Return value
114
115The return value of the library is an array of replacement results against each file that was processed. This includes files in which no replacements were made.
116
117Each result contains the following values:
118
119- `file`: The path to the file that was processed
120- `hasChanged`: Flag to indicate if the file was changed or not
121
122```js
123const results = replace.sync({
124 files: 'path/to/files/*.html',
125 from: /foo/g,
126 to: 'bar',
127});
128
129console.log(results);
130
131// [
132// {
133// file: 'path/to/files/file1.html',
134// hasChanged: true,
135// },
136// {
137// file: 'path/to/files/file2.html',
138// hasChanged: true,
139// },
140// {
141// file: 'path/to/files/file3.html',
142// hasChanged: false,
143// },
144// ]
145
146```
147
148To get an array of changed files, simply map the results as follows:
149
150```js
151const changedFiles = results
152 .filter(result => result.hasChanged)
153 .map(result => result.file);
154```
155
156### Counting matches and replacements
157By setting the `countMatches` configuration flag to `true`, the number of matches and replacements per file will be counted and present in the results array.
158
159- `numMatches`: Indicates the number of times a match was found in the file
160- `numReplacements`: Indicates the number of times a replacement was made in the file
161
162Note that the number of matches can be higher than the number of replacements if a match and replacement are the same string.
163
164```js
165const results = replace.sync({
166 files: 'path/to/files/*.html',
167 from: /foo/g,
168 to: 'bar',
169 countMatches: true,
170});
171
172console.log(results);
173
174// [
175// {
176// file: 'path/to/files/file1.html',
177// hasChanged: true,
178// numMatches: 3,
179// numReplacements: 3,
180// },
181// {
182// file: 'path/to/files/file2.html',
183// hasChanged: true,
184// numMatches: 1,
185// numReplacements: 1,
186// },
187// {
188// file: 'path/to/files/file3.html',
189// hasChanged: false,
190// numMatches: 0,
191// numReplacements: 0,
192// },
193// ]
194```
195
196## Advanced usage
197
198### Replace a single file or glob
199```js
200const options = {
201 files: 'path/to/file',
202};
203```
204
205### Replace multiple files or globs
206
207```js
208const options = {
209 files: [
210 'path/to/file',
211 'path/to/other/file',
212 'path/to/files/*.html',
213 'another/**/*.path',
214 ],
215};
216```
217
218### Replace first occurrence only
219
220```js
221const options = {
222 from: 'foo',
223 to: 'bar',
224};
225```
226
227### Replace all occurrences
228Please 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_.
229
230To replace multiple occurrences at once, you must use a regular expression for the `from` parameter with the global flag enabled, e.g. `/foo/g`.
231
232```js
233const options = {
234 from: /foo/g,
235 to: 'bar',
236};
237```
238
239### Multiple values with the same replacement
240
241These will be replaced sequentially.
242
243```js
244const options = {
245 from: [/foo/g, /baz/g],
246 to: 'bar',
247};
248```
249
250### Multiple values with different replacements
251
252These will be replaced sequentially.
253
254```js
255const options = {
256 from: [/foo/g, /baz/g],
257 to: ['bar', 'bax'],
258};
259```
260
261### Custom regular expressions
262
263Use the [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) constructor to create any regular expression.
264
265```js
266const str = 'foo';
267const regex = new RegExp('^' + str + 'bar', 'i');
268const options = {
269 from: regex,
270 to: 'bar',
271};
272```
273
274### Using callbacks for `from`
275You 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:
276
277```js
278const options = {
279 files: 'path/to/file',
280 from: (file) => new RegExp(file, 'g'),
281 to: 'bar',
282};
283```
284
285### Using callbacks for `to`
286As 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:
287
288```js
289const options = {
290 files: 'path/to/file',
291 from: /SomePattern[A-Za-z-]+/g,
292 to: (match) => match.toLowerCase(),
293};
294```
295
296This 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:
297
298```js
299const options = {
300 files: 'path/to/file',
301 from: /SomePattern[A-Za-z-]+/g,
302 to: (...args) => args.pop(),
303};
304```
305
306### Ignore a single file or glob
307
308```js
309const options = {
310 ignore: 'path/to/ignored/file',
311};
312```
313
314### Ignore multiple files or globs
315
316```js
317const options = {
318 ignore: [
319 'path/to/ignored/file',
320 'path/to/other/ignored_file',
321 'path/to/ignored_files/*.html',
322 'another/**/*.ignore',
323 ],
324};
325```
326
327Please 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 `./**/*`.
328
329### Allow empty/invalid paths
330If set to true, empty or invalid paths will fail silently and no error will be thrown. For asynchronous replacement only. Defaults to `false`.
331
332```js
333const options = {
334 allowEmptyPaths: true,
335};
336```
337
338### Disable globs
339You 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`.
340
341```js
342const options = {
343 disableGlobs: true,
344};
345```
346
347### Specify glob configuration
348Specify configuration passed to the `glob` call:
349
350```js
351const options = {
352 glob: {
353 //Glob settings here
354 },
355};
356```
357
358Please note that the setting `nodir` will always be passed as `false`.
359
360### Making replacements on network drives
361To make replacements in files on network drives, you may need to specify the UNC path as the `cwd` config option. This will then be passed to glob and prefixed to your paths accordingly. See [#56](https://github.com/adamreisnz/replace-in-file/issues/56) for more details.
362
363### Specify character encoding
364Use a different character encoding for reading/writing files. Defaults to `utf-8`.
365
366```js
367const options = {
368 encoding: 'utf8',
369};
370```
371
372### Dry run
373To do a dry run without actually making replacements, for testing purposes. Defaults to `false`.
374
375```js
376const options = {
377 dry: true,
378};
379```
380
381## CLI usage
382
383```sh
384replace-in-file from to some/file.js,some/**/glob.js
385 [--configFile=replace-config.js]
386 [--ignore=ignore/files.js,ignore/**/glob.js]
387 [--encoding=utf-8]
388 [--disableGlobs]
389 [--isRegex]
390 [--verbose]
391 [--quiet]
392 [--dry]
393```
394
395Multiple files or globs can be replaced by providing a comma separated list.
396
397The flags `--disableGlobs`, `--ignore` and `--encoding` are supported in the CLI.
398
399The setting `allowEmptyPaths` is not supported in the CLI as the replacement is
400synchronous, and this setting is only relevant for asynchronous replacement.
401
402To list the changed files, use the `--verbose` flag. Success output can be suppressed by using the `--quiet` flag.
403
404To do a dry run without making any actual changes, use `--dry`.
405
406A regular expression may be used for the `from` parameter by specifying the `--isRegex` flag.
407
408The `from` and `to` parameters, as well as the files list, can be omitted if you provide this
409information in a configuration file. You can provide a path to a configuration file
410(either Javascript or JSON) with the `--configFile` flag. This path will be resolved using
411Node’s built in `path.resolve()`, so you can pass in an absolute or relative path.
412
413## Version information
414From 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.
415
416See the [Changelog](CHANGELOG.md) for more information.
417
418## License
419(MIT License)
420
421Copyright 2015-2019, [Adam Reis](https://adam.reis.nz), Co-founder at [Hello Club](https://helloclub.com/?source=npm)