|
| 1 | +const fs = require('fs'); |
| 2 | +const { spawn: spawnDefault, exec: execDefault } = require('child_process'); |
| 3 | + |
| 4 | +const exec = (command, cb) => { |
| 5 | + execDefault(command, { |
| 6 | + maxBuffer: 1024 * 1024, |
| 7 | + }, cb); |
| 8 | +}; |
| 9 | +const spawn = (command, cb) => { |
| 10 | + const split = command.split(' '); |
| 11 | + const program = split[0]; |
| 12 | + const args = split.slice(1); |
| 13 | + const child = spawnDefault(program, args || []); |
| 14 | + const outputList = []; |
| 15 | + child.stdout.setEncoding('utf8'); |
| 16 | + child.stderr.setEncoding('utf8'); |
| 17 | + child.stdout.on('data', (data) => outputList.push(data) && console.log(data.replace(/\n$/, ''))); |
| 18 | + child.stderr.on('data', (data) => outputList.push(data) && console.log(data.replace(/\n$/, ''))); |
| 19 | + child.on('close', (code) => code === 1 ? cb(new Error(`child process exited with code ${code}`, [outputList.join('')])) : cb(null, [outputList.join('')])); |
| 20 | +}; |
| 21 | + |
| 22 | +const sedReplace = (input, before, after, output, cb = () => {}) => { |
| 23 | + const file = fs.readFileSync(input, 'utf8'); |
| 24 | + const re = new RegExp(escapeRegExp(before), 'gm'); |
| 25 | + const newFile = file.replace(re, after); |
| 26 | + fs.writeFileSync(output, newFile, 'utf8'); |
| 27 | + cb(); |
| 28 | +}; |
| 29 | + |
| 30 | +function escapeRegExp(text) { |
| 31 | + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); |
| 32 | +} |
| 33 | + |
| 34 | +module.exports = { |
| 35 | + exec, |
| 36 | + spawn, |
| 37 | + sedReplace, |
| 38 | +}; |
0 commit comments