1

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.

L.T
  • 2,539
  • 3
  • 20
  • 30

1 Answers1

0

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.

Tarang
  • 75,157
  • 39
  • 215
  • 276
  • Thanks for input. but when I ```n.send({ hello: 'world',Test:Test });``` in ```Meteor.startup```. in children.js can't get function ```say``` – L.T Dec 23 '13 at 09:13
  • Not very sure of the types of data you can pass, you can pass arguments but not sure about entire objects because its a separate process. See http://stackoverflow.com/questions/15368436/fork-a-child-process-and-inject-dependency – Tarang Dec 23 '13 at 12:06