node.jselectronvitenode.js-fs

fs.watch doesn't return an FSWatcher instance in Electron


I have an Electron React App

Where I'm trying to call .close() on the object that I assigned an fs.watch to. But I think Vite, Electron or something is wrapping something around the object returned from fs.watch so it's not an FSWatcher, since .close() does not exist on this object.

let watcher = window.api.watch(file1, (eventType, filename) => {})
setTimeout(() => {
    console.log(watcher)
    watcher.close() // Breaks inside Electron
    watcher = window.api.watch(file2, (eventType, filename) => {})
}, 5000)

There's some security stuff going on so you have to expose Node features through a preloader:

import fs from 'fs'

const api = {
    watch: fs.watch
}

Which is what I'm calling in the first snippet.

If I run the first snippet directly through Node then it works just fine.

If I run it through my Vite/Electron wrapper then it says .close is not a function.

When I log out what my watcher is when it doesn't work, it looks like this:

{
  _events: {
    change: ƒ
  },
  _eventsCount: 1,
  _maxListeners: undefined,
  _handle: {
    Symbol(owner_symbol): {},
    onchange: ƒ
  },
  [Symbol(kCapture)]: false,
  [Symbol(shapeMode)]: false
}

Anyone know how I can close my fs.watch properly inside of Electron/Vite?

Edit: The actual .watching of the first file works perfectly fine. I just can't close it.


Solution

  • A solution is to implement the bridge between your renderer and Node can be done through the preloader and IPC. I still don't know why the considerably less tedious way to do it - as listed in the question - does not work, but not a lot of traction on the question to find that out.