title: Webworker-threads in Node.JS
body: <p>I am a NodeJS newbie from C# world still trying to understand the complex JavaScript maze.
  I am trying to implement the multi-threading from the example on <a href="https://www.npmjs.com/package/webworker-threads" rel="nofollow noreferrer">https://www.npmjs.com/package/webworker-threads</a>. </p>
  
  <p>Can not understand why the below works:</p>
  
  <pre><code>var Worker = require('webworker-threads').Worker;
  var FibCalculator = require('./FibCalculator.js');
  
  require('http').createServer(function (req,res) {
    console.log('request received.');
    var fibo = new Worker(function() {
      var calcFib = function (n) {
        return n &gt; 1 ? calcFib(n - 1) + calcFib(n - 2) : 1;
      };
      this.onmessage = function (event) {
        postMessage(calcFib(event.data));
      };
    });
    fibo.onmessage = function (event) {
      var msg = 'fib(5) = ' + event.data;
      console.log(msg);
      res.end(msg);
    };
    fibo.postMessage(5);
  }).listen(3000);
  </code></pre>
  
  <p>But the below just does not</p>
  
  <pre><code>var Worker = require('webworker-threads').Worker;
  var FibCalculator = require('./FibCalculator.js');
  
  //the below function just does not get called
  var calcFib = function (n) {
      console.log('***This will not print. Can someone explain why?***');
      return n &gt; 1 ? calcFib(n - 1) + calcFib(n - 2) : 1;
  };
  
  require('http').createServer(function (req,res) {
    console.log('request received.');
    var fibo = new Worker(function() {    
      this.onmessage = function (event) {
        postMessage(calcFib(event.data));
      };
    });
    fibo.onmessage = function (event) {
      var msg = 'fib(5) = ' + event.data;
      console.log(msg);
      res.end(msg);
    };
    fibo.postMessage(5);
  }).listen(3000);
  </code></pre>
  
  <p>Why is it that if I take out the scope of calcFib, it cannot get called. My idea was to implement a wrapper over webworker-threads that could be used to perform any CPU intrinsic operations on another thread. However, I am not even able to call an external function </p>
  
  <p><strong>Below is reply to Benjamin Gruenbaum answer:</strong></p>
  
  <p>How can I call console.log inside onmessage but not my function defined outside the scope in the same file?</p>
  
  <pre><code>this.onmessage = function (event) {
    console.log('can call console.log even if it is external');
    //cannot call calcFib(event.data) if it is defined outside the scope.
    postMessage(calcFib(event.data));
  };
  </code></pre>