2

i wanted to get only filename being changed,removed,rename but i'm getting full file path

Question: i wanted to get full filename being changed rather path or doing string on full path

here is what i'm trying:

  var fileLocation = path.join(__dirname, 'folder/');

    var watcher = chokidar.watch(fileLocation, {
        persistent: true
      });

      watcher
      .on('add', path => {console.log(`File ${path} has been added name:`); })
      .on('change', path => {console.log(`File ${path} has been changed`);});
      .on('unlink', path => { console.log(`File ${path} has been removed`); });
EaBengaluru
  • 131
  • 2
  • 17
  • 59
  • see https://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript – Hoff Oct 22 '18 at 13:14

2 Answers2

4

Since chokidar is based on the glob library it has a build in functionality that allows you to specify the working directory directly by setting the cwd option. So simply change your code to:

var fileLocation = path.join(__dirname, 'folder/');

var watcher = chokidar.watch(".", {
    persistent: true,
    cwd: fileLocation
});

and you will get just a file name in path.

Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
0

or you can try another way.

watcher.on('change', path => {

  const fileIndex = path.lastIndexOf('/') + 1;
  const fileFullName = path.substr(fileIndex);
  const filePureName = fileFullName.split('.')[0];
});
Haojen
  • 686
  • 7
  • 9