Can't wait without a fiber when calling Meteor.users.findOne - meteor

I'm consuming a message from RabbitMQ and then want to send a push notification to APNS/GSM using raix-push plugin. I have RabbitMQ integrated with Meteor but when I try to query the user's record for their _id (required for raix-push), it gives this exception:
W20150930-16:03:53.929(-7)? (STDERR) Error: [Error: Can't wait without a fiber]
W20150930-16:03:53.929(-7)? (STDERR) at Connection.<anonymous> (packages/jakobloekke_rabbitmq/packages/jakobloekke_rabbitmq.js:20:1)
W20150930-16:03:53.929(-7)? (STDERR) at Connection.emit (events.js:117:20)
W20150930-16:03:53.929(-7)? (STDERR) at Connection.<anonymous> (/Users/lsacco/.meteor/packages/jakobloekke_rabbitmq/.0.0.2.1lqodho++os+web.browser+web.cordova/npm/node_modules/amqp/lib/connection.js:176:14)
W20150930-16:03:53.930(-7)? (STDERR) at Connection.emit (events.js:95:17)
W20150930-16:03:53.930(-7)? (STDERR) at CleartextStream.emit (events.js:95:17)
W20150930-16:03:53.933(-7)? (STDERR) at CleartextStream.<anonymous> (_stream_readable.js:765:14)
W20150930-16:03:53.933(-7)? (STDERR) at CleartextStream.emit (events.js:92:17)
W20150930-16:03:53.933(-7)? (STDERR) at emitReadable_ (_stream_readable.js:427:10)
W20150930-16:03:53.933(-7)? (STDERR) at _stream_readable.js:420:7
W20150930-16:03:53.933(-7)? (STDERR) at process._tickCallback (node.js:448:13)
I've tried many different things to such as wrapping as Fiber, using Meteor.bindEnivornment and the approach mentioned here. Any idea what I'm missing here?
RabbitMQ.connection.on('ready', function () {
RabbitMQ.connection.queue('ma.services.gapns', {'durable': true, 'autoDelete': false, closeChannelOnUnsubscribe: true }, function (queue) {
try
queue.bind('ma.integration.exchange', 'gapns');
queue.subscribe(function (msg) {
var data = {};
if (msg.content) {
data = msg.content;
}
var uid = data.uid,
system = data.system,
count = data.count;
if (uid && system && count >= 0) {
var user = getUser(uid);
Push.send({
from: 'push',
title: 'Hub Notification',
text: system + " request(s) to approve",
badge: count,
sound: 'ping.aiff',
query: {
userId: user._id
}
});
}
});
}
catch (e) {
logger.error("Exception occurred while processing push notifications: " + e);
}
});
});
function getUser(uid) {
var Future = Npm.require('fibers/future');
var future = new Future();
Meteor.users.findOne({username: uid}, {}, function(err, result) {
if (err) {
future.throw(err);
}
future.return(result);
});
return future.wait();
}

I had to add Meteor.bindEnvironment() to all three callbacks (connection ready, connection queue, and queue subscribe) for this to work. That eluded me because I thought if the top level function had it, I'd be ok.

Related

Using Meteor wrapAync and/or bindEnvironment when calling function in methods.js using async function in fixtures.js

My Meteor project has the DASH SDK installed as an NPM package. The goal is to call the "funds" function in methods.js from fixtures.js whenever a transaction is received. The address and amount are console logging from fixtures.js correctly, but I am receiving an error regarding bindEnvironment due to fibers. It does not console log from methods.js.
fixtures.js
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
const Dash = require("dash");
const mnemonic = 'fake fake fake fake fake fake fake fake fake fake fake fake';
const client = new Dash.Client({ network: "testnet", wallet: { mnemonic } });
async function listenUnconfirmedTransaction() {
const account = await client.wallet.getAccount();
console.log(account);
account.on('FETCHED/CONFIRMED_TRANSACTION', (data) => {
console.dir(data);
var amount = data.payload.transaction.outputs[0]._satoshis;
var address = data.payload.transaction.outputs[0].script.toAddress("testnet").toString();
console.log("Amount: " + amount + ", Address: " + address);
if (address) {
Meteor.call('funds', address, amount, (error) => { if (error) { console.log(error); }});
};
});
};
listenUnconfirmedTransaction();
}
methods.js
import { Meteor } from 'meteor/meteor';
Meteor.methods({
'funds': function (address, received) {
console.log("Address: " + address + ", Received: " + received);
}
});
I have looked into the bindEnvironment and wrapAsync for Meteor, but I am not understanding how I can use them in this situation. Please advise
EDIT
Error:
I20220918-19:58:40.577(-7)? Amount: 200000000, Address: yQKFphqFK7yWSCzxor9SthWwL9Z17u4TyJ
I20220918-19:58:40.624(-7)? error: Error syncing incoming transactions Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment. Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
I20220918-19:58:40.625(-7)? at Object.Meteor._nodeCodeMustBeInFiber (packages/meteor.js:1188:11)
I20220918-19:58:40.625(-7)? at Meteor.EnvironmentVariable.EVp.get (packages/meteor.js:1213:10)
I20220918-19:58:40.625(-7)? at Server.applyAsync (packages/ddp-server/livedata_server.js:1774:64)
I20220918-19:58:40.626(-7)? at Server.apply (packages/ddp-server/livedata_server.js:1739:26)
I20220918-19:58:40.626(-7)? at Server.call (packages/ddp-server/livedata_server.js:1721:17)
I20220918-19:58:40.626(-7)? at Account.<anonymous> (server/main.js:16:20)
I20220918-19:58:40.626(-7)? at Account.emit (events.js:400:28)
I20220918-19:58:40.626(-7)? at Account.emit (domain.js:475:12)
I20220918-19:58:40.626(-7)? at Storage.<anonymous> (/home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/Account/Account.js:107:72)
I20220918-19:58:40.626(-7)? at Storage.emit (events.js:400:28)
I20220918-19:58:40.627(-7)? at Storage.emit (domain.js:475:12)
I20220918-19:58:40.627(-7)? at ChainStore.<anonymous> (/home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/Storage/methods/createChainStore.js:21:14)
I20220918-19:58:40.628(-7)? at ChainStore.emit (events.js:400:28)
I20220918-19:58:40.628(-7)? at ChainStore.emit (domain.js:475:12)
I20220918-19:58:40.629(-7)? at ChainStore.considerTransaction (/home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/ChainStore/methods/considerTransaction.js:92:10)
I20220918-19:58:40.630(-7)? at /home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/Account/methods/importTransactions.js:31:46
W20220918-19:58:40.630(-7)? (STDERR) (node:2339) UnhandledPromiseRejectionWarning: Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
W20220918-19:58:40.631(-7)? (STDERR) at Object.Meteor._nodeCodeMustBeInFiber (packages/meteor.js:1188:11)
W20220918-19:58:40.632(-7)? (STDERR) at Meteor.EnvironmentVariable.EVp.get (packages/meteor.js:1213:10)
W20220918-19:58:40.632(-7)? (STDERR) at Server.applyAsync (packages/ddp-server/livedata_server.js:1774:64)
W20220918-19:58:40.632(-7)? (STDERR) at Server.apply (packages/ddp-server/livedata_server.js:1739:26)
W20220918-19:58:40.633(-7)? (STDERR) at Server.call (packages/ddp-server/livedata_server.js:1721:17)
W20220918-19:58:40.633(-7)? (STDERR) at Account.<anonymous> (server/main.js:16:20)
W20220918-19:58:40.633(-7)? (STDERR) at Account.emit (events.js:400:28)
W20220918-19:58:40.634(-7)? (STDERR) at Account.emit (domain.js:475:12)
W20220918-19:58:40.634(-7)? (STDERR) at Storage.<anonymous> (/home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/Account/Account.js:107:72)
W20220918-19:58:40.634(-7)? (STDERR) at Storage.emit (events.js:400:28)
W20220918-19:58:40.635(-7)? (STDERR) at Storage.emit (domain.js:475:12)
W20220918-19:58:40.635(-7)? (STDERR) at ChainStore.<anonymous> (/home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/Storage/methods/createChainStore.js:21:14)
W20220918-19:58:40.635(-7)? (STDERR) at ChainStore.emit (events.js:400:28)
W20220918-19:58:40.636(-7)? (STDERR) at ChainStore.emit (domain.js:475:12)
W20220918-19:58:40.636(-7)? (STDERR) at ChainStore.considerTransaction (/home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/ChainStore/methods/considerTransaction.js:92:10)
W20220918-19:58:40.637(-7)? (STDERR) at /home/alexanderwshea/Meteor/dashreceiver/node_modules/#dashevo/wallet-lib/src/types/Account/methods/importTransactions.js:31:46
W20220918-19:58:40.637(-7)? (STDERR) (Use `node --trace-warnings ...` to show where the warning was created)
W20220918-19:58:40.637(-7)? (STDERR) (node:2339) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
W20220918-19:58:40.638(-7)? (STDERR) (node:2339) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Ok, if you run Meteor up to version 2.7.3 you need to wrap that(details further down).
2.8 is now in preparation and it makes the move from Fibers (still compatible with NodeJS 14 but not with Node 16) to async. I think async now works server side, just keep an eye on this: https://forums.meteor.com/t/eta-of-2-8-release/58720
Wrapping for Fibers. This is basically running async code as if it was synchronous.
const bound = Meteor.bindEnvironment(callback => callback())
bound(() => {
...your code goes here.
})

Moment.js and formatting on server side

Need to know:
I'm using the latest version of meteor
I'm using the latest version of moment.js
This code is on the server side
var date = moment(new Date());
console.log(date.format("YYYY-MM-DD HH:mm:ss.SS"));
I end up with this error
SyncedCron: Exception "count daily parks per spot" ReferenceError: moment is not defined
at spotIDList.forEach (app/server/main.js:66:18)
at SynchronousCursor.forEach (packages/mongo/mongo_driver.js:1054:16)
at Cursor.(anonymous function) [as forEach] (packages/mongo/mongo_driver.js:876:44)
at Object.job (app/server/main.js:62:16)
at packages/percolate_synced-cron.js:242:26
at scheduleTimeout (packages/percolate_synced-cron.js:290:7)
at packages/percolate_synced-cron.js:338:42
at Meteor.EnvironmentVariable.EVp.withValue (packages/meteor.js:1186:26)
at packages/meteor.js:502:25
at runWithEnvironment (packages/meteor.js:1238:24)
the snippet above comes from the following code
SyncedCron.add({
name: 'Simple Cron Function',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('every 15 second');
},
job: function(intendedAt) {
var spotList = spots.find({});
spotList.forEach((spot) => {
var devaddr = `${spot.devaddr}`;
var date = moment(new Date());
console.log(date.format("YYYY-MM-DD HH:mm:ss.SS"));
var dailyVisitsCount = log.find(
{
devaddr : devaddr,
car : "1",
createdAt: {
$gte: date.format("YYYY-MM-DD HH:mm:ss.SS")
}
},
{
sort: {
createdAt:1
}
}
).count();
spots.update({devaddr : devaddr}, { $set: {numberOfParksToday: dailyVisitsCount } } , {multi: false}, function(err, res) {
if (err) throw err;
});
console.log("Daily Visits Count Updated to " + dailyVisitsCount);
});
}
});
Any insight to why this block of code is not working the way it should that would be appreciates.
I did find out that this problem occurred due to a bug in a previous release of meteor which has been fixed.
I'm just trying to get today's date in a format my DB accepts and use that to filter my results. alternative suggestions is also welcomed.
PS: Momnet.js works for me in different locations(client side code)
EDIT:
W20180312-08:03:15.324(-7)? (STDERR) app/server/main.js:1
W20180312-08:03:15.325(-7)? (STDERR) (function(Npm,Assets){(function(){import moment from 'moment'
W20180312-08:03:15.325(-7)? (STDERR) ^^^^^^
W20180312-08:03:15.325(-7)? (STDERR)
W20180312-08:03:15.325(-7)? (STDERR) SyntaxError: Unexpected reserved word
W20180312-08:03:15.326(-7)? (STDERR) at Object.exports.runInThisContext (vm.js:53:16)
W20180312-08:03:15.327(-7)? (STDERR) at /home/elder/Desktop/Recreation-of-ParkeyeDashboard/ParkeyeDashboard/.meteor/local/build/programs/server/boot.js:289:30
W20180312-08:03:15.327(-7)? (STDERR) at Array.forEach (native)
W20180312-08:03:15.329(-7)? (STDERR) at Function._.each._.forEach (/home/elder/.meteor/packages/meteor-tool/.1.4.2_3.14963jl++os.linux.x86_64+web.browser+web.cordova/mt-os.linux.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20180312-08:03:15.330(-7)? (STDERR) at /home/elder/Desktop/Recreation-of-ParkeyeDashboard/ParkeyeDashboard/.meteor/local/build/programs/server/boot.js:128:5
W20180312-08:03:15.330(-7)? (STDERR) at /home/elder/Desktop/Recreation-of-ParkeyeDashboard/ParkeyeDashboard/.meteor/local/build/programs/server/boot.js:344:5
W20180312-08:03:15.330(-7)? (STDERR) at Function.run (/home/elder/Desktop/Recreation-of-ParkeyeDashboard/ParkeyeDashboard/.meteor/local/build/programs/server/profile.js:480:12)
W20180312-08:03:15.331(-7)? (STDERR) at /home/elder/Desktop/Recreation-of-ParkeyeDashboard/ParkeyeDashboard/.meteor/local/build/programs/server/boot.js:343:11
You need to install the moment.js package:
meteor npm i --save moment
Then at the top of your file you need to import moment:
import moment from 'moment'
Then to get the date in a format the DB will accept using moment just do:
var date = moment().toDate()
Using moment() creates a moment object of the current date/time. Running toDate() on it gives you the same date/time in a Date object.

Meteor 1.3 update migration

I'm just working through the update to 1.3 and not sure how to handle this error. I'm thinking it might have to do with file load order changing in 1.3. Any ideas? Thanks!
W20160407-09:54:43.528(1)? (STDERR) /Users/technical/.meteor/packages/meteor-tool/.1.3.1.10rlef4++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:267
W20160407-09:54:43.528(1)? (STDERR) throw(ex);
W20160407-09:54:43.528(1)? (STDERR) ^
W20160407-09:54:43.553(1)? (STDERR) TypeError: Cannot read property 'path' of undefined
W20160407-09:54:43.553(1)? (STDERR) at Routing (packages/lookback:emails/lib/routing.js:17:9)
W20160407-09:54:43.554(1)? (STDERR) at packages/lookback:emails/lib/mailer.js:279:11
W20160407-09:54:43.554(1)? (STDERR) at Array.forEach (native)
W20160407-09:54:43.554(1)? (STDERR) at packages/lookback:emails/lib/mailer.js:278:28
W20160407-09:54:43.554(1)? (STDERR) at Function._.each._.forEach (packages/underscore.js:147:22)
W20160407-09:54:43.554(1)? (STDERR) at Object.init (packages/lookback:emails/lib/mailer.js:274:9)
W20160407-09:54:43.554(1)? (STDERR) at Object.Mailer.init (packages/lookback:emails/lib/mailer.js:303:7)
W20160407-09:54:43.554(1)? (STDERR) at app/server/lib/config/config.js:72:8
W20160407-09:54:43.554(1)? (STDERR) at /Users/technical/code/mssc1.3/.meteor/local/build/programs/server/boot.js:290:5
server/lib/config/config.js
Meteor.startup(function() {
this.Templates = {}
Templates.remindEventEmail = {
path: 'remindEventEmail.html'
};
Mailer.init({
templates: Templates
});
});
private/remindEventEmail.html
<p>Email code<p>
it's not a 1.3 thing, it's a lookback > 0.7.0 thing
if you don't need email previews, simply setting
Mailer.config({
addRoutes: false
});
may fix your problem.
otherwise follow along for how I use it with Flow Router
according to:
you now need to supply a route field on your template object
https://github.com/lookback/meteor-emails#version-history
route: {
path: '/sample/:name',
// params is an object, with potentially named parameters, and a `query` property
// for a potential query string.
data: function(params) {
// `this` is the HTTP response object.
return {
name: params.name // instead of this.params.name
};
}
}
so your
Templates.remindEventEmail = {
path: 'remindEventEmail.html'
};
should become
Templates.remindEventEmail = {
path: 'remindEventEmail.html'
route: {
path: '/event/:_id/remind',
data: function(params) {
return {
event: Events.findOne(params._id);
}
}
}
};
the actual route would then be /emails/event/:_id/remind
please notice the data pattern, you might use another style of query or nesting of the main data context

Download of previously stored document in Meteor fails

My meteor application does not download previously stored documents.
Initially I thought I was having problems with ongoworks:security support for CollectionFS.
RsrchDocs.files.permit(['download']).apply() causes Invalid key errors. Have read the ongoworks:security docs and CollectionFS docs multiple times without finding my error. The Github repository for "ongoworks:security issues 4, 17, 20 appear to address this problem. It is not clear that the issues raised were ever fully resolved. I have tried the suggestions without success. Since RsrchDocs.allow({...}) (option B) allows the server to (re)start without error I may (probably?) have another error preventing the download.
With option A or B in place, hovering over the download link in the browser displays the correct URL, but clicking the link does not initiate the download. Manually copying the URL into the address field and submitting that does successfully download the document.
What should I do/change in my meteor app to successfully download a previously stored document?
server/security.js
RsrchDocs.files.permit(['insert', 'update', 'remove']).apply();
// Option A:
// Uncommented causes "(STDERR) Error: EBADF, read" on (re)start
// Document download is NOT permitted.
//Security.permit(['download']).collections([RsrchDocs]).apply();
// Option B:
// Uncommented (re)starts without any error message
// Document download is NOT permitted
//RsrchDocs.allow({
// download: function(userId, doc){
// return true;
// }
//});
// Option C:
// Uncommented (re)starting meteor causes multiline error message
// Server start fails
//RsrchDocs.files.permit(['download']).apply();
// The error messages:
[[[[[ C:\Users\loco\My Projects\Meteor\research ]]]]]
=> Started proxy.
=> Started MongoDB.
I20150817-10:38:58.532(-5)? Meteor._wrapAsync has been renamed to Meteor.wrapAsync
=> Started your app.
=> App running at: http://localhost:3000/
Type Control-C twice to stop.
(STDERR) Error: EBADF, read
Meteor._wrapAsync has been renamed to Meteor.wrapAsync
(STDERR)
(STDERR) C:\Users\loco\AppData\Local\.meteor\packages\meteor-tool\1.1.4\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\fibers\future.js:245
(STDERR) throw(ex);
(STDERR) ^
(STDERR) Error: allow: Invalid key: download
(STDERR) at packages/mongo/collection.js:723:1
(STDERR) at Array.forEach (native)
(STDERR) at Function._.each._.forEach (packages/underscore/underscore.js:105:1)
(STDERR) at [object Object].addValidator (packages/mongo/collection.js:721:1)
(STDERR) at [object Object].Mongo.Collection.allow (packages/mongo/collection.js:769:1)
(STDERR) at packages/ongoworks:security/security-util.js:39:1
(STDERR) at Array.forEach (native)
(STDERR) at Function._.each._.forEach (packages/underscore/underscore.js:105:1)
(STDERR) at addFuncForAll (packages/ongoworks:security/security-util.js:38:1)
(STDERR) at packages/ongoworks:security/security-util.js:56:1
(STDERR) at Array.forEach (native)
(STDERR) at Function._.each._.forEach (packages/underscore/underscore.js:105:1)
(STDERR) at ensureCreated (packages/ongoworks:security/security-util.js:52:1)
(STDERR) at ensureDefaultAllow (packages/ongoworks:security/security-util.js:70:1)
(STDERR) at SecurityRuleConstructor.Security.Rule.apply (packages/ongoworks:security/security-api.js:76:1)
(STDERR) at app\server\security.js:18:38
(STDERR) at app\server\security.js:22:3
(STDERR) at C:\Users\loco\My Projects\Meteor\research\.meteor\local\build\programs\server\boot.js:222:10
(STDERR) at Array.forEach (native)
(STDERR) at Function._.each._.forEach (C:\Users\loco\AppData\Local\.meteor\packages\meteor-tool\1.1.4\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\underscore\underscore.js:79:11)
(STDERR) at C:\Users\loco\My Projects\Meteor\research\.meteor\local\build\programs\server\boot.js:117:5
=> Exited with code: 8
Meteor._wrapAsync has been renamed to Meteor.wrapAsync
lib/collections/rsrchDocs.js
RsrchDocs = new FS.Collection("rsrchDocs", {
stores: [new FS.Store.FileSystem("rsrchDocs")]
});
if(Meteor.isClient){
Meteor.subscribe('RsrchDocs')
}
// server/publish.js
Meteor.publish('RsrchDocs', function(){
return RsrchDocs.find({});
});
client/documents/templates.html
<template name='subjDocs'>
<div id='upload' class='upload'>
{{> upload}}
</div>
<div class="col-xs-12" id="docsTable">
{{> reactiveTable collection=subjDocs settings=docSettings }}
</div>
</template>
client/documents/helpers.js
Template.subjDocs.helpers({
subjDocs: function() {
return RsrchDocs.find({ 'metadata.subjId': this._id });
},
docSettings: function(){
return {
fields: [
{ key: 'metadata.subjId', label: 'Subject', hidden: false },
// ...
{ key: 'original.name', label: 'Name',
fn: function(value, object) {
var docName = value;
var dnloadURL = object.url({download: true});
var linkStr = "<a href= '"+dnloadURL+"' >"+docName+"</a>";
return Spacebars.SafeString(linkStr);
},
},
],
};
}
});
client/documents/events.js
Template.subjDocs.events({
'click .reactive-table tr': function (event) {
event.preventDefault();
var subjDoc = this;
switch (event.target.className) {
case 'delete':
if( confirm && subjDoc ) {
subjDoc.remove()
};
return false;
break;
//case ...
};
},
});
Environment:
Windows 7
C:\Users\ ... \research>meteor list
accounts-password 1.1.1
alanning:roles 1.2.13
aldeed:autoform 5.4.1
aldeed:collection2 2.3.3
aldeed:simple-schema 1.3.3
aslagle:reactive-table 0.8.11
cfs:ejson-file 0.1.4
cfs:filesystem 0.1.2
cfs:gridfs 0.0.33
cfs:standard-packages 0.5.9
cfs:ui 0.1.3
email 1.0.6
fortawesome:fontawesome 4.4.0
ian:accounts-ui-bootstrap-3 1.2.77
iron:router 1.0.9
meteor-platform 1.2.2
ongoworks:security 1.2.0
raix:ui-dropped-event 0.0.7
reactive-var 1.0.5
sanjo:jasmine 0.17.0
twbs:bootstrap 3.3.5
velocity:html-reporter 0.8.2

how to use child_process.fork in meteor

I test the code in meteor .There are some errors.
/server/lib/Test.js
Test = {
say:function(){
console.log("hello world");
}
}
/server/main.js
Meteor.startup(function(){
Test.say(); //work well
var path = Npm.require('path');
var base = path.resolve('.');
var n = Npm.require('child_process').fork(base+"/app/server/children.js");
n.on('message', function(m) {
console.log('PARENT got message:', m);
});
n.send({ hello: 'world' });
});
/server/children.js
process.on('message', function(m) {
Test.say(); //throw a error . The Test is undefined
console.log('CHILD got message:', m);
process.send({name:"ABC"});
});
process.send({ foo: 'bar' });
errors:
I20131223-16:34:44.717(8)? hello world
W20131223-16:34:44.784(8)? (STDERR) /home/ec/workspace/meteor/testChildrenProcess/.meteor/local/build/programs/server/app/server/children.js:2
W20131223-16:34:44.784(8)? (STDERR) Test.say();
W20131223-16:34:44.785(8)? (STDERR) ^
W20131223-16:34:44.785(8)? (STDERR) ReferenceError: Test is not defined
W20131223-16:34:44.787(8)? (STDERR) at process. (/home/ec/workspace/meteor/testChildrenProcess/.meteor/local/build/programs/server/app/server/children.js:2:3)
W20131223-16:34:44.788(8)? (STDERR) at process.EventEmitter.emit (events.js:98:17)
W20131223-16:34:44.788(8)? (STDERR) at handleMessage (child_process.js:318:10)
W20131223-16:34:44.788(8)? (STDERR) at Pipe.channel.onread (child_process.js:345:11)
The Test Object is undefined in "/app/server/children.js" bu it's normal in main.js.
Why? Have I forgotten anything? Any help is appreciated.
The variables are scoped. While in Meteor Test would be available to the other files in your meteor project they are not available to Npm modules/stuff required by Npm.require.
The children.js would be in a different namespace to your main.js file. To access the Test variable in it you would need to pass it a param or as a message.

Resources