0

I'm running node.js on Ubuntu 18.04 LTS. I appear to be getting different behaviour using require depending on whether I use it in the REPL or in a script. Specifically, I used npm to download lightstreamer-client-node. Now, I open up a terminal and do the following:

colin@colin-XPS-15-9550:~$ node
> var x = require('lightstreamer-client-node')

This works perfectly.

Now I want to use this package in a script. I create a text file node_test.js containing just the line:

var x = require('lightstreamer-client-node')

and I open up a terminal and run the command:

colin@colin-XPS-15-9550:~$ node /home/colin/node_test.js

This hangs indefinitely on a blinking cursor.

I'm brand new to node.js and JavaScript so perhaps this is expected behaviour. I've done some reading about the require function and can't seem to find an explanation for it. Note that if I replace lightstreamer-client-node with some other node module, e.g. safe-buffer, then everything works fine, whether I use REPL or script.

tycrek
  • 168
  • 1
  • 13
Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89
  • 1
    what happens if you put a second line ... like `console.log('hello world')` after the require statement? – Jaromanda X Apr 09 '20 at 04:04
  • 1
    Have you tried putting more code in your file? I was able to `require` it, and with the require being the only thing in the file it did hang like you said. However, I put a bunch of random print statements in. They printed fine, but then hung. I then added `process.exit(0);` to the end of the script and it exited normally. Perhaps the hang is expected of that specific package. – tycrek Apr 09 '20 at 04:05
  • @JaromandaX Thanks for responding. I just placed `console.log('message 1')` before the `require` and `console.log('message 2')` after the `require`. Both statements printed, then the blinking cursor. – Colin T Bowers Apr 09 '20 at 04:05
  • 1
    so, it's not the require that is preventing the node process from ending - it's something in that library that does that - possibly for a good reason - who knows, but you can safely write code that uses that library – Jaromanda X Apr 09 '20 at 04:07
  • @tycrek I just duplicated that on my machine. Thanks for responding. Perhaps it is supposed to happen. LightStreamer is for establishing a bi-directional connection with a server, so I guess it sort of makes sense? I'm brand new to this area of programming, so my question is perhaps a bit naive. – Colin T Bowers Apr 09 '20 at 04:09
  • @JaromandaX Awesome thanks. My question may have been naive. – Colin T Bowers Apr 09 '20 at 04:12
  • It's not a naive question at all – Jaromanda X Apr 09 '20 at 04:14

1 Answers1

2

The process seems to hang because the library lightstreamer-client installs a timer, with the function setInterval, for its internal activities, and nodejs doesn't allow a graceful shutdown when there are active tasks. So the only way to terminate the script is by using the function process.exit.