runok
Version:
NPM scripts on steroids! Replace your scripts with pure JS
44 lines (43 loc) • 1.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const task_1 = require("../task");
const result_1 = require("../result");
const fs = require('fs');
const path = require('path');
function replaceInFile(file, configFn) {
const config = new ReplaceInFileConfig(file);
config.apply(configFn);
const result = result_1.Result.start(config.TASK, config.file);
let data;
try {
data = fs.readFileSync(file).toString();
for (const r of config.replaceList) {
data = replaceAll(data, r['from'], r['to']);
}
fs.writeFileSync(file, data);
}
catch (error) {
return result.fail(error);
}
return result.success();
}
exports.default = replaceInFile;
class ReplaceInFileConfig extends task_1.TaskConfig {
constructor(file) {
super();
this.file = file;
this.TASK = 'replaceInFile';
this.replaceList = [];
}
replace(from, to) {
this.replaceList.push({
from, to
});
}
}
function replaceAll(string, from, to) {
if (typeof from === 'string') {
return string.split(from).join(to);
}
return string.replace(from, to);
}