file.js 873B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const fs = require('fs')
  2. function fileInsert (path, insStr, insSign, avoidDupSign) {
  3. fileReadAndWrite(path, function (data) {
  4. if (avoidDupSign && data.indexOf(avoidDupSign) !== -1) return
  5. const position = data.indexOf(insSign)
  6. return data.slice(0, position) + insStr + data.slice(position)
  7. })
  8. }
  9. function fileReplace (path, search, replace) {
  10. fileReadAndWrite(path, function (data) {
  11. return data.replace(new RegExp(search, 'g'), replace)
  12. })
  13. }
  14. function fileReadAndWrite (path, callback) {
  15. if (!fs.existsSync(path)) return
  16. const encoding = 'utf8'
  17. let data = null
  18. try {
  19. data = fs.readFileSync(path, encoding)
  20. } catch (e) {
  21. return console.error(e)
  22. }
  23. const result = callback(data)
  24. try {
  25. fs.writeFileSync(path, result, encoding)
  26. } catch (e) {
  27. console.error(e)
  28. }
  29. }
  30. module.exports = {
  31. fileInsert,
  32. fileReplace
  33. }