Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

sed.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var common = require('./common');
  2. var fs = require('fs');
  3. //@
  4. //@ ### sed([options ,] search_regex, replacement, file)
  5. //@ Available options:
  6. //@
  7. //@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_
  8. //@
  9. //@ Examples:
  10. //@
  11. //@ ```javascript
  12. //@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js');
  13. //@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js');
  14. //@ ```
  15. //@
  16. //@ Reads an input string from `file` and performs a JavaScript `replace()` on the input
  17. //@ using the given search regex and replacement string or function. Returns the new string after replacement.
  18. function _sed(options, regex, replacement, file) {
  19. options = common.parseOptions(options, {
  20. 'i': 'inplace'
  21. });
  22. if (typeof replacement === 'string' || typeof replacement === 'function')
  23. replacement = replacement; // no-op
  24. else if (typeof replacement === 'number')
  25. replacement = replacement.toString(); // fallback
  26. else
  27. common.error('invalid replacement string');
  28. if (!file)
  29. common.error('no file given');
  30. if (!fs.existsSync(file))
  31. common.error('no such file or directory: ' + file);
  32. var result = fs.readFileSync(file, 'utf8').replace(regex, replacement);
  33. if (options.inplace)
  34. fs.writeFileSync(file, result, 'utf8');
  35. return common.ShellString(result);
  36. }
  37. module.exports = _sed;