Search code examples
javascripthtmlnode.jsv8

addEventListener in independent javascript without it being part of html file


I have too many high level questions on javascript. While I am doing my research to understand these one by one, some quick pointers/insights would help a lot.

I understand that we can add eventListener on DOM elements in javascript inside html file, but I have a question on when writing javascript as a separate, standalone script without it being part of html -- say server side.

Can we add eventListener here as well?, because here we don't have any DOM element reference. Ideally, I want to be able to do something like:

addEventListener('keypress', logKey);

function logKey(e) {
  console.log("Hello, World!");
}

and then expect this program to run indefinitely and everytime someone hits key, the log would be printed. I tried and it doesn't work. I want to gain insight on what is wrong with this and if there is any workaround to achieve something like this.

Edit: The use case is that I want javascript program to run indefinitely (like how client side javascript runs) and everytime I hit a key (without enter), it should log on console. I am trying to understand that why the same addEventListener syntax that we use on client side inside html file with DOM element doesn't work on server side...


Solution

  • No, actually you cannot add browser specific event listeners to server side javascript (e.g nodejs).

    In server side javascript you can write Command Line Interface (CLI) applications in which you can listen to several different events which normally you listen to when you write client side javascript but with different syntax and listeners of course.