Usage of atom.project.onDidChangeFiles()


#1

Hi,

I am a newbie!
Can anyone please help in explaining how the command atom.project.onDidChangeFiles() can be used, please provide an example other than already mentioned in the docs.
Also, please provide a brief example in a manner like where this functions can be written.

Any help would be greatly appreciated!


#2

Hi!

According to the documentation, the command atom.projects.onDidChangeFiles is used to perform a function (the callback) when the relevant event is emitted. In this case, it activates when there is a change in the file system of an open project (the set of folders in the tree view).

Was there anything specific you needed?

For me, the function speaks for itself. It will activate when an observed file is created, modified, deleted, or renamed. When it activates, it will pass an array of objects as the argument to the callback you provided. It passes an array of them, because several different events could happen before the emitter has time to trigger. To prevent a drop in performance (from repeatedly triggering in quick sucession), it groups them all together into the one array.

The objects are described in the docs, with the action property being a string of the type of event ("created", "modified", etc.), the path property being the absolute path of the relevant file, and the oldPath being there when the event is "rename", as it holds the old name.

The return value of the function itself is a disposable, so it must be added to a disposables instance. For example, the following can be pasted into your init.js script (you may have an init.coffee; you can translate the following into CoffeeScript if you prefer).

const { CompositeDisposable } = require("atom");

let disposables = new CompositeDisposable();
disposables.add(
  atom.project.onDidChangeFiles(myCallback)
);

function myCallback(array) {
  console.log(...array); // unpack the array and pretend the elements were passed as separate arguments
}

Playing around with it, you will see it logs the objects whenever a watched file is saved, renamed, or deleted.

For examples of it’s use out in the wild, just search for it on GitHub


#3

Thank you for your help!