Beginner: usage example for chokidar in Meteor to prevent Error: Meteor code must always run within a Fiber


#1

The code below gives me the Error: ‘Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.’

import chokidar from ‘chokidar’;
import { Meteor } from ‘meteor/meteor’;
import { Mongo } from ‘meteor/mongo’;
const Plates = new Mongo.Collection(‘plates’);

var path = ‘~/Documents/dev/lpr/test’;
var watcher = chokidar.watch(path, {
ignored: /(^|[/\])…/,
persistent: true
});
watcher.on(‘add’, path => {
console.log(DEBUG: File ${path} has been added);
Plates.insert({
path,
})
});
The Meteor documentation (https://guide.meteor.com/using-npm-packages.html#wrap-async) suggests using Meteor.wrapAsync to solve this issue but I don’t understand how to apply in this case?

e.g. below returns ‘TypeError: watcherFiber.on is not a function’

var watcherFiber = Meteor.wrapAsync(chokidar.watch(path, {
ignored: /(^|[/\])…/,
persistent: true
}));

watcherFiber
.on(‘add’, path => {
console.log(DEBUG: File ${path} has been added);
Plates.insert({
path,
})
});


#2

This was the solution that worked for me.

watcher.on(‘add’, Meteor.bindEnvironment(path => {
console.log(DEBUG: File ${path} has been added);
Plates.insert({
path,
});
}));