DePhoegon

Control File Watch

Mar 9th, 2020
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs')
  2. const readline = require('readline')
  3. var fp = 'e:/Test/watch/control.txt'
  4. var fml = 'e:/Test/watch/control2.txt'
  5. var file = fs.readFileSync(fp)
  6. var cnt = 0
  7.  
  8. // console.log('Initial File content: \n' + file)
  9. // 0o111 is read only flag for windows || 0o222 Write flag
  10. // Used to lock  a given file to prevent alterations in the middle of processing the  file.
  11. function rwlock(file, rw) {
  12.     if (rw === 'r') { rw = 0o111 }
  13.     if (rw === 'w') { rw = 0o222 }
  14.     fs.chmod (file, rw, (err) => {
  15.         if (err) throw err
  16.         // code for successful change.
  17.     })
  18. }
  19. // appeand file puts the data at the end of file, \n is the 'end of line' character.
  20. function filerb(file, line) {
  21.     fs.appendFile(file, line + '\n', (err) => {
  22.         if (err) throw err
  23.     })
  24. }
  25. // inputfile = file || linne = The line to be modified in the duplicate file.
  26. // reads file & creates a duplicate file, with a modified line using the count of the lines as a control method
  27. // Can execute code on reading the file, keywords & careful planning of control files.
  28. function ProcessFile(inputfile, linne) {
  29.         ins = fs.createReadStream(inputfile)
  30.         outs = new (require('stream'))()
  31.         rl = readline.createInterface(ins, outs)
  32.         cnt = 0
  33.  
  34.     rl.on('line', (line) => {
  35.         cnt = cnt+1
  36.         if (cnt === linne || cnt === linne+2) {
  37.             console.log(line + ' - ' + cnt)
  38.             line = line + ' - Modified - Line count > ' + cnt
  39. //            filerb(fml, line)
  40.         } else {
  41. //            filerb(fml, line)
  42.         }
  43.     })
  44.  
  45.     rl.on('close', (line)=> {
  46.         console.log('done reading file.')
  47.     })
  48. }
  49.  
  50. fs.watchFile(fp, { persistent: true, interval: 100 }, ()=> {
  51.     console.log('File changed .. ')
  52.     file = fs.readFileSync(fp)
  53.     console.log('File content at : ' + new Date())
  54.     // Space for checking for file changes on a watched file. executes when file 'changes' including saves/syncs
  55.  //   ProcessFile(fp, 2)
  56. })
  57.  
  58. // WIP *DePhoegon
Add Comment
Please, Sign In to add comment