I am writing a VSCode extension and I need a way to know when a project gets a new dependency to trigger some action. For that, I decided to watch package.json file using 'fs.watchFile'. But the problem is that fs sees the change only after saving the file and it takes a second or two. Moreover, if a user adds a new dependency manually to package.json there is no change event until the user saves it. I wonder if VSCode has some internal API that will do it better than fs.
VSCode has a nice utility for that vscode.workspace.createFileSystemWatcher. It's better than fs implementation because it is also triggered when the file is 'dirty' before it is saved. Possible implementation is:
const watcher = vscode.workspace.createFileSystemWatcher(
packageJsonPath, // absolute path to package.json
true, // ignore create events
false, // don't ignore change events
true, // ignore delete events
);
watcher.onDidChange(() => {
// trigger some action
})
// when not needed
if (watcher) {
watcher.dispose();
}