Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
replace-in-file
Advanced tools
The replace-in-file npm package allows you to easily search and replace text in files. It is useful for tasks such as updating configuration files, modifying source code, and performing batch text replacements.
Basic Replacement
This feature allows you to perform a basic search and replace operation in a specified file. The 'from' field can be a string or a regular expression, and the 'to' field is the replacement string.
const replace = require('replace-in-file');
const options = {
files: 'path/to/file.txt',
from: /oldText/g,
to: 'newText',
};
replace(options)
.then(results => console.log('Replacement results:', results))
.catch(error => console.error('Error occurred:', error));
Multiple Replacements
This feature allows you to perform multiple search and replace operations in a single file. The 'from' and 'to' fields are arrays, where each element in 'from' is replaced by the corresponding element in 'to'.
const replace = require('replace-in-file');
const options = {
files: 'path/to/file.txt',
from: [/oldText1/g, /oldText2/g],
to: ['newText1', 'newText2'],
};
replace(options)
.then(results => console.log('Replacement results:', results))
.catch(error => console.error('Error occurred:', error));
Glob Pattern Matching
This feature allows you to use glob patterns to specify multiple files for the search and replace operation. This is useful for batch processing multiple files in a directory.
const replace = require('replace-in-file');
const options = {
files: 'path/to/*.txt',
from: /oldText/g,
to: 'newText',
};
replace(options)
.then(results => console.log('Replacement results:', results))
.catch(error => console.error('Error occurred:', error));
Dry Run
This feature allows you to perform a dry run of the search and replace operation. No actual changes are made to the files, but you can see what the results would be. This is useful for testing your replacement logic before applying it.
const replace = require('replace-in-file');
const options = {
files: 'path/to/file.txt',
from: /oldText/g,
to: 'newText',
dry: true,
};
replace(options)
.then(results => console.log('Dry run results:', results))
.catch(error => console.error('Error occurred:', error));
The 'replace' package is another tool for performing search and replace operations in files. It offers similar functionality to 'replace-in-file' but with a simpler API. It is suitable for straightforward replacement tasks.
The 'string-replace-loader' package is a webpack loader that allows you to perform string replacements in your source files during the build process. It is useful for replacing text in JavaScript and other files as part of your build pipeline.
The 'gulp-replace' package is a plugin for the Gulp task runner that allows you to perform search and replace operations in your Gulp streams. It integrates well with Gulp workflows and is useful for automating text replacements in your build process.
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.
from
to
# Using npm, installing to local project
npm i --save replace-in-file
# Using npm, installing globally for global cli usage
npm i -g replace-in-file
# Using yarn
yarn add replace-in-file
//Load the library and specify options
const replace = require('replace-in-file');
const options = {
files: 'path/to/file',
from: /foo/g,
to: 'bar',
};
async
/await
try {
const results = await replace(options)
console.log('Replacement results:', results);
}
catch (error) {
console.error('Error occurred:', error);
}
replace(options)
.then(results => {
console.log('Replacement results:', results);
})
.catch(error => {
console.error('Error occurred:', error);
});
replace(options, (error, results) => {
if (error) {
return console.error('Error occurred:', error);
}
console.log('Replacement results:', results);
});
try {
const results = replace.sync(options);
console.log('Replacement results:', results);
}
catch (error) {
console.error('Error occurred:', error);
}
The 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.
Each result contains the following values:
file
: The path to the file that was processedhasChanged
: Flag to indicate if the file was changed or notconst results = replace.sync({
files: 'path/to/files/*.html',
from: /foo/g,
to: 'bar',
});
console.log(results);
// [
// {
// file: 'path/to/files/file1.html',
// hasChanged: true,
// },
// {
// file: 'path/to/files/file2.html',
// hasChanged: true,
// },
// {
// file: 'path/to/files/file3.html',
// hasChanged: false,
// },
// ]
To get an array of changed files, simply map the results as follows:
const changedFiles = results
.filter(result => result.hasChanged)
.map(result => result.file);
By setting the countMatches
configuration flag to true
, the number of matches and replacements per file will be counted and present in the results array.
numMatches
: Indicates the number of times a match was found in the filenumReplacements
: Indicates the number of times a replacement was made in the fileNote that the number of matches can be higher than the number of replacements if a match and replacement are the same string.
const results = replace.sync({
files: 'path/to/files/*.html',
from: /foo/g,
to: 'bar',
countMatches: true,
});
console.log(results);
// [
// {
// file: 'path/to/files/file1.html',
// hasChanged: true,
// numMatches: 3,
// numReplacements: 3,
// },
// {
// file: 'path/to/files/file2.html',
// hasChanged: true,
// numMatches: 1,
// numReplacements: 1,
// },
// {
// file: 'path/to/files/file3.html',
// hasChanged: false,
// numMatches: 0,
// numReplacements: 0,
// },
// ]
const options = {
files: 'path/to/file',
};
const options = {
files: [
'path/to/file',
'path/to/other/file',
'path/to/files/*.html',
'another/**/*.path',
],
};
const options = {
from: 'foo',
to: 'bar',
};
Please note that the value specified in the from
parameter is passed straight to the native String replace method. As such, if you pass a string as the from
parameter, it will only replace the first occurrence.
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
.
const options = {
from: /foo/g,
to: 'bar',
};
These will be replaced sequentially.
const options = {
from: [/foo/g, /baz/g],
to: 'bar',
};
These will be replaced sequentially.
const options = {
from: [/foo/g, /baz/g],
to: ['bar', 'bax'],
};
Use the RegExp constructor to create any regular expression.
const str = 'foo';
const regex = new RegExp('^' + str + 'bar', 'i');
const options = {
from: regex,
to: 'bar',
};
from
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:
const options = {
files: 'path/to/file',
from: (file) => new RegExp(file, 'g'),
to: 'bar',
};
to
As the to
parameter is passed to the native String replace method, you can also specify a callback. The following example uses a callback to convert matching strings to lowercase:
const options = {
files: 'path/to/file',
from: /SomePattern[A-Za-z-]+/g,
to: (match) => match.toLowerCase(),
};
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:
const options = {
files: 'path/to/file',
from: /SomePattern[A-Za-z-]+/g,
to: (...args) => args.pop(),
};
const options = {
ignore: 'path/to/ignored/file',
};
const options = {
ignore: [
'path/to/ignored/file',
'path/to/other/ignored_file',
'path/to/ignored_files/*.html',
'another/**/*.ignore',
],
};
Please note that there is an open issue with Glob 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 ./**/*
.
If set to true, empty or invalid paths will fail silently and no error will be thrown. For asynchronous replacement only. Defaults to false
.
const options = {
allowEmptyPaths: true,
};
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
.
const options = {
disableGlobs: true,
};
Specify configuration passed to the glob
call:
const options = {
glob: {
//Glob settings here
},
};
Please note that the setting nodir
will always be passed as false
.
To 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 for more details.
Use a different character encoding for reading/writing files. Defaults to utf-8
.
const options = {
encoding: 'utf8',
};
To do a dry run without actually making replacements, for testing purposes. Defaults to false
.
const options = {
dry: true,
};
replace-in-file from to some/file.js,some/**/glob.js
[--configFile=replace-config.js]
[--ignore=ignore/files.js,ignore/**/glob.js]
[--encoding=utf-8]
[--disableGlobs]
[--isRegex]
[--verbose]
[--quiet]
[--dry]
Multiple files or globs can be replaced by providing a comma separated list.
The flags --disableGlobs
, --ignore
and --encoding
are supported in the CLI.
The setting allowEmptyPaths
is not supported in the CLI as the replacement is
synchronous, and this setting is only relevant for asynchronous replacement.
To list the changed files, use the --verbose
flag. Success output can be suppressed by using the --quiet
flag.
To do a dry run without making any actual changes, use --dry
.
A regular expression may be used for the from
parameter by specifying the --isRegex
flag.
The from
and to
parameters, as well as the files list, can be omitted if you provide this
information in a configuration file. You can provide a path to a configuration file
(either Javascript or JSON) with the --configFile
flag. This path will be resolved using
Node’s built in path.resolve()
, so you can pass in an absolute or relative path.
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.
See the Changelog for more information.
(MIT License)
Copyright 2015-2019, Adam Reis, Co-founder at Hello Club
4.0.0
The return value is now a results array instead of an array with changed files. The new results array includes each file that was processed, with a flag to indicate whether or not the file was changed, and optionally information about the number of matches and replacements that were made. See the readme for more details.
To update existing code and obtain an array of changed files again, simply convert the results array as follows:
const results = await replace(options);
const changedFiles = results
.filter(result => result.hasChanged)
.map(result => result.file);
FAQs
A simple utility to quickly replace text in one or more files.
The npm package replace-in-file receives a total of 708,668 weekly downloads. As such, replace-in-file popularity was classified as popular.
We found that replace-in-file demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.