klaurtar1
klaurtar1

Reputation: 788

How to use EventEmitter in Node.js

I created a small Express server in Node.js with a singular route. When an HTTP request is used to GET '/get-jobs' I want to emit an event that communicates said event to another file that send s an axios request to console.log the data on a page URL I specify. However, for some reason my EventEmitter is not correctly listening on the axios file. How can I fix this?

Here is my entry point:

import express from 'express';
import dotenv from 'dotenv';

import EventEmitter from './EventEmitter.js';

const app = express();
dotenv.config({ path: './config.env' });

app.use(express.json());

app.get('/get-jobs', (req, res) => {
  console.log('Route was hit');
  EventEmitter.emit('getJobs', req);
});

app.listen(process.env.PORT, () => {
  console.log(`Listening on port ${process.env.PORT}...`);
});

Here is my axios job file that is currently not listening:

import axios from 'axios';
import EventEmitter from './EventEmitter.js';

EventEmitter.on('getJobs', () => {
    await main();
  console.log('Test');
});

async function main() {
  try {
    const { data } = await axios.get(
      'https://www.monster.com/jobs/search/?q=javascript&where=Saint-Louis__2C-MO&stpage=1&page=4'
    );

    console.log(data);
  } catch (err) {
    console.log(err);
  }
}

And here is my event emitter file:

import EventEmitter from 'events';

export default new EventEmitter();

Upvotes: 2

Views: 1711

Answers (1)

Nedal Eldeen
Nedal Eldeen

Reputation: 169

Simply, because you didn't include the (axios-containing) file in your app. The file that listens to events hasn't started yet. So, try to import the file in your running app. And don't forget to add async keyword in your case.

EventEmitter.on('getJobs', async () => { await ...

Remember that we listen to events before we publish them. Hope this answer helps.

Upvotes: 3

Related Questions