0

I am new to node and I am trying learn the different ways you can use export module to make my code easier to read because they are in separate files. I have want to take my program response functions out of my callback.js file and move them into a separate file called progresponse.js but I am getting errors because it is not reading the emit method on the emitter.js file. The emitter.js and callback.js code works. But I am trying to get the emitter.js, wanttomodularize.js and progresponses.js code to work.

my progresponses.js and wanttomodularize.js code was my attempt at separating that code. This code gives the error that it doesn't recognize some emitter.js methods.

I apologize ahead of time if this is a lot and very specific to my learning but could someone show me how I can take the bolded text out of callback.js and put it into a separate file (progresponse.js)?

emitter.js

function Emitter(){
  this.events = {};
}

Emitter.prototype.on = function( type, listener){
  this.events[type] = this.events[type] || [];
  this.events[type].push(listener);
}

Emitter.prototype.emit = function(type){
  if(this.events[type]){
    this.events[type].forEach(function(listner){
      listner();
    });
   }
}

module.exports = Emitter;

callback.js (this code works with emitter.js)

var Emitter = require('./emitter.js'); 

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'Speak Chinese> '
});

var user = {
  "name" : "something",
  "response" : ""
};

var emtr = new Emitter();

function 你好(callback) {

  var data = {
      programResponse: '你好!'
  };

  console.log(data.programResponse);
  callback(data);
}

function 你在干什么(callback) {

  emtr.on('你在干什么', function(){
    console.log('我在喝咖啡。');
    console.log(user.name +',你呢,你在干什么?');
  });

  callback();
}

function 你猜猜(callback) {

  emtr.on('你猜猜', function(){
    console.log('我不知道。'+ user.name +',你在干什么?');
  });

  callback();
}

function 对(callback) {
  emtr.on('对', function(){
    console.log('真棒');
  });

  callback();
}

rl.question('What is your name? ', (answer) => {
  // TODO: Log the answer in a database
  user.name = answer;
  console.log(`Thank you for your valuable feedback: ${answer}`);
});

rl.prompt();

rl.on('line', (line) => {
  switch (line.trim()) {
    case '你好':你好(function(){}); 
      break;
    case '你在干什么':你在干什么(function(){emtr.emit('你在干什么')});
      break;
    case '你猜猜':你猜猜(function(){emtr.emit('你猜猜')});
      break;
    case '对':对(function(){emtr.emit('对')});   
      break;
    default:
      console.log(`Interesting, you said '${line.trim()}'?`);
      break;
  }
  rl.prompt();
}).on('close', () => {
  console.log('再见!');
  process.exit(0);
});

wanttomodularize.js

var Emitter = require('./emitter.js'); 
var callback = require('./progresponses.js');
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'Speak Chinese> '
});

var user = {
  "name" : "something",
  "response" : ""
};


rl.question('What is your name? ', (answer) => {
  // TODO: Log the answer in a database
  user.name = answer;
  console.log(`Thank you for your valuable feedback: ${answer}`);
});

rl.prompt();

rl.on('line', (line) => {
  switch (line.trim()) {
    case '你好':callback.你好(function(){}); 
      break;
    case '你在干什么':callback.你在干什么(function(){callback.emtr.emit('你在干什么')});
      break;
    case '你猜猜':callback.你猜猜(function(){callback.emtr.emit('你猜猜')});
      break;
    case '对':callback.对(function(){callback.emtr.emit('对')});   
      break;
    default:
      console.log(`Interesting, you said '${line.trim()}'?`);
      break;
  }
  rl.prompt();
}).on('close', () => {
  console.log('再见!');
  process.exit(0);
});

progresponses.js

var Emitter = require('./emitter.js'); 
var emtr = new Emitter();

module.exports = {
  你好: function 你好(callback) {

    var data = {
        programResponse: '你好!'
    };

    console.log(data.programResponse);
    callback(data);
  },
  你在干什么: function 你在干什么(callback) {

    emtr.on('你在干什么', function(){
      console.log('我在喝咖啡。');
      console.log(user.name +',你呢,你在干什么?');
    });

    callback();
  },
  你猜猜: function 你猜猜(callback) {

    emtr.on('你猜猜', function(){
      console.log('我不知道。'+ user.name +',你在干什么?');
    });

    callback();
  },
  对: function 对(callback) {

    emtr.on('对', function(){
      console.log('真棒');
    });

    callback();
  }
}

This is the error I get when running:

node wanttomodularize.js

Bretts-MacBook-Pro:clinput codesankofa$ node wanttomodularize.js
What is your name? DOM
Thank you for your valuable feedback: DOM
你在干什么
readline.js:1021
            throw err;
            ^

TypeError: Cannot read property 'emit' of undefined
    at /Users/codesankofa/CodingWorkspace/NodePractice/clinput/wanttomodularize.js:28:58
    at Object.你在干什么 (/Users/codesankofa/CodingWorkspace/NodePractice/clinput/progresponses.js:21:5)
    at Interface.rl.on (/Users/codesankofa/CodingWorkspace/NodePractice/clinput/wanttomodularize.js:28:27)
    at emitOne (events.js:116:13)
    at Interface.emit (events.js:211:7)
    at Interface._onLine (readline.js:282:10)
    at Interface._line (readline.js:631:8)
    at Interface._ttyWrite (readline.js:911:14)
    at ReadStream.onkeypress (readline.js:160:10)
    at emitTwo (events.js:126:13)
6
  • are all your files in the same folder? Commented Aug 10, 2018 at 19:27
  • I see that you are exporting progresponses.js but are not exporting wanttomodularize.js, that may be the error. What error bursts for you? Are all files in the same directory? Commented Aug 10, 2018 at 19:34
  • I added the error to the main question at the bottom @HenriqueViana Commented Aug 10, 2018 at 20:13
  • @joseatchang. Yes all files are in the same folder. Commented Aug 10, 2018 at 20:17
  • wanttomodularize.js is the mail file I want to run. It does not seem that because all of the files are in the same directory (callback.js and wanttomodularize.js) is causing the problem. I moved wanttomodularize.js to it's own folder with emitter.js and progresponses.js and got the same error. Commented Aug 10, 2018 at 20:25

2 Answers 2

1

You are using emtr from callback, but you have not assigned it to the exported object. You need to include it before exporting.

//wanttomodularize.js

var callback = require('./progresponses.js');
//...
callback.emtr.emit

// progresponses.js

module.exports = {
  emtr, // <-----

  你好: function 你好(callback) {

    var data = {
        programResponse: '你好!'
    };

    console.log(data.programResponse);
    callback(data);
  },
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I ran into one more problem because of my code. I didn't define or pass the username information into the progresponse.js file. so I passed that along with the function. This is really helping me learn. I appreciate it. I'll try to explain the issue better in the question so others can search for it.
You can return a factory function from the module to take your parameter. That's a good design, but another issue...
1

The emtr is undefined because it is not a global function within its module, it is inside another function.

Another detail is that you need to return the callback, with an emit name, to be able to use it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.