replace-in-file
Version:
A simple utility to quickly replace text in one or more files.
53 lines (52 loc) • 1.93 kB
JavaScript
import { parseConfig } from "./helpers/config.js";
import { logDryRun } from "./helpers/handlers.js";
import { pathsSync, pathsAsync } from "./helpers/paths.js";
import { replaceSync, replaceAsync } from "./helpers/replace.js";
import { replaceStreamAsync } from "./helpers/stream.js";
import { processFile, processFileSync } from "./process-file.js";
/**
* Replace in file (async)
*/
export async function replaceInFile(config) {
//If custom processor is provided use it instead
if (config && (config.processor || config.processorAsync)) {
return await processFile(config);
}
//Parse config
const parsed = parseConfig(config);
const { files, from, to, dry, verbose, streaming } = parsed;
//Dry run?
logDryRun(dry && verbose);
//Find paths and process them, streaming if configured
const replace = streaming ? replaceStreamAsync : replaceAsync;
const paths = await pathsAsync(files, parsed);
const promises = paths.map(path => replace(path, from, to, parsed));
const results = await Promise.all(promises);
//Return results
return results;
}
/**
* Replace in file (sync)
*/
export function replaceInFileSync(config) {
if (config && config.processorAsync) {
throw new Error('ProcessorAsync cannot be used in synchronous mode');
}
if (config && config.streaming) {
throw new Error('Streaming cannot be used in synchronous mode');
}
//If custom processor is provided use it instead
if (config && config.processor) {
return processFileSync(config);
}
//Parse config
const parsed = parseConfig(config);
const { files, from, to, dry, verbose } = parsed;
//Dry run?
logDryRun(dry && verbose);
//Find paths and process them
const paths = pathsSync(files, parsed);
const results = paths.map(path => replaceSync(path, from, to, parsed));
//Return results
return results;
}