Watch a folder for changes using node.js, and print file paths when they are changed

后端 未结 3 793
误落风尘
误落风尘 2020-11-30 18:33

I\'m trying to write a node.js script that watches for changes in a directory of files, and then prints the files that are changed. How can I modify this script so that it w

相关标签:
3条回答
  • 2020-11-30 18:46

    try hound:

    hound = require('hound')
    
    // Create a directory tree watcher.
    watcher = hound.watch('/tmp')
    
    // Create a file watcher.
    watcher = hound.watch('/tmp/file.txt')
    
    // Add callbacks for file and directory events.  The change event only applies
    // to files.
    watcher.on('create', function(file, stats) {
      console.log(file + ' was created')
    })
    watcher.on('change', function(file, stats) {
      console.log(file + ' was changed')
    })
    watcher.on('delete', function(file) {
      console.log(file + ' was deleted')
    })
    
    // Unwatch specific files or directories.
    watcher.unwatch('/tmp/another_file')
    
    // Unwatch all watched files and directories.
    watcher.clear()
    

    It will execute once file was change

    0 讨论(0)
  • 2020-11-30 18:55

    Try Chokidar:

    var chokidar = require('chokidar');
    
    var watcher = chokidar.watch('file or dir', {ignored: /^\./, persistent: true});
    
    watcher
      .on('add', function(path) {console.log('File', path, 'has been added');})
      .on('change', function(path) {console.log('File', path, 'has been changed');})
      .on('unlink', function(path) {console.log('File', path, 'has been removed');})
      .on('error', function(error) {console.error('Error happened', error);})
    

    Chokidar solves some of the crossplatform issues with watching files using just fs.

    0 讨论(0)
  • 2020-11-30 19:04

    Why not just use the old fs.watch? Its pretty straightforward.

    fs.watch('/path/to/folder', (eventType, filename) => {
    console.log(eventType);
    // could be either 'rename' or 'change'. new file event and delete
    // also generally emit 'rename'
    console.log(filename);
    })
    

    For more info and details about the options param, see Node fs Docs

    0 讨论(0)
提交回复
热议问题