Eric's Advanced Web Scripting Workspace

Butler Community College Spring 2026

Code Explanation

We made a simple eventEmitter that reads input from the command line and executes code to change that value.

const eventEmitter = require('events');
const customEmitter = new eventEmitter();
const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);

These are just variable declarations to call in modules that we need from Node. The first line calls in the events module and assigns it eventEmitter(). From there we can make a new eventEmitter called customEmitter to edit. The next line calls in the readline module and rl modifies readline to accept input from the console.

customEmitter.on('mess', (radius) => {
    if (isNaN(radius)) {
        console.log('Sorry, couldn\'t figure out the circumference. Please enter a real number next time.');
    } else {
    let circRaw = 2 * Math.PI * radius;
    let circ = circRaw.toFixed(2);
    console.log(`The circumference is ${circ} units.`);
}
});

The first line creates a listener that waits for an event called 'mess' to be fired and receives 'radius' as an argument. 'if (isNan(radius))' is a quick validation check. If they input a string instead of a number then it will return an error message. Then we create a new variable called circRaw that holds the values of 2 times Pi times the radius argument. Then we create a circ variable that rounds up circRaw to two decimal places. Finally, we make a message that displays our new modified value in the console.

customEmitter.on('mess', () => {
    // console.log('Data received.');
    rl.question('What?', (ans) => {
        console.log('Data received.');
        console.log(`Your answer is ${ans}.`);
        rl.close();
    })
});

The line is similar to the first line above. It listens for an event called 'mess' to be fired. Unlike before, it doesn't pass a parameter. The second line is commented out. The third line uses our rl variable from earlier to queue a question to the console. It waits for input and assigns it to an 'ans' variable. After getting an answer back, the console write "Data received. Your answer is (user input)." Finally, it closes the readline to close the query.

customEmitter.emit('mess', 27);

This line fires the 'mess' event and passes 27 as an argument. So, 27 would fill the radius variable in the first customEmitter above.