node.js: program either exits unexpectedly or just hangs - javascript

I wrote a module in node.js that performs some network operation. I wrote a small script that uses this module (the variable check below). It looks like this:
check(obj, function (err, results) {
// ...
console.log("Check completed");
});
Now here is the interesting thing. When this code executes as part of a mocha test, the test exits as expected. I see the log statement printed and the process exits.
When the code is executed as a standalone node script, the log statement gets printed, but the process just hangs.
When I try to debug it and I start the program using --debug-brk and use node-inspector, it exits early! I see that process.on 'exit' is called. It exits while some internal callbacks within the module weren't called yet. So the log statement above isn't printed either.
I am stuck now and am not sure why this is happening. Has anyone seen similar behaviour?

When you run it as a script and it hangs when "done", it means node still has callbacks registered waiting for events. Node doesn't know that those events won't fire anymore. You can either just call process.exit() if you know it's time to exit, or you can explicitly close/unbind/disconnect everything (network connections, db connections, etc). If you properly close everything, node should then exit.
The module wtfnode (mentioned by Nathan Arthur) or why-is-node-running can be really helpful tracking this down.

If the program exits unexpectedly, it can be because the event loop becomes empty and there is nothing else to do (because some code forgot to emit an error or do something else to keep the event loop going). In this case Node exits with code 0 and you won't get any error messages whatsoever, so it can be really confusing.
See https://github.com/archiverjs/node-archiver/issues/457 for an example of this happening.

Related

Selenium with nodejs- a process not stop even if the error comes, the issue facing on 107.XX version of chrome browser and chrome driver

I am working in NODE JS (javascript) with selenium webdriver.
Package.json-
“chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7.1.3”, “moment”: “^2.29.4”, “selenium-webdriver”: “^4.5.0”, “selenium-standalone”: “^8.2.3"
file1.js
it("Test code", async function(){ console.log("START"); await driver.sleep(3000); console.log("HELLO); await driver.findElement(Xpath).sendKeys("TEXT"); console.log("STOP"); })
the problem has been coming when updating the chrome driver or chrome browser, the issue is when the old code runs and when it doesn't. So is there any problem with this latest version or what?.
EX. I want to run my code like by like TOP to Bottom, which means first run the first line then after next so on, so I am put await driver.sleep(3000), which means the process hold at least 3 sec then after running next step, here before update the version it's working as expected but now some time its work and sometimes not, also not getting an error if found any error during runtime, currently process shows continues ongoing. Even if we put timeout then also not stop after time reach,
if remove the "await" command then do not run sync mode.
really confused what's going on. not getting errors and the process taking more and more time means not stopping automatically.
It may not fix your problem, but you will need to make sure that you have quotes around the word 'Hello' when you are trying to console.log it.
console.log("HELLO);
Should be:
console.log("HELLO");

Node.js application exits without throwing errors

I'm experiencing a weird issue with nodejs, my application quits without throwing any error or logging anything into the console. The whole code runs in a while (true) loop, I checked all of the if/else and try/catch blocks and the code never has a reason to stop, in fact this happens after running for some hours without any issue.
I've also tried adding a general error handler on the main function of the application like this:
try {
start()
} catch(err) {
utils.logMessage(`General Error: ${err}`, 'red')
utils.sendErrorWebhook(err)
}
It didn't change anything though, and when checking logs everything runs smooth and then suddenly stops.
Has anyone ever experienced this issue or know how to fix? Main modules I'm using are the mongodb official client (not mongoose) and axios.

TestCafe Runner.run(runOptions) never returns, browser hangs (Firefox & Chrome)

I've got a little sandbox project I've been playing around with for the last few weeks to learn the in's and out's of implementing a TestCafe runner.
I've managed to solve all my problems except one and at this point I've tried everything I can think of.
Reviewed the following similar questions:
How to close testcafe runner
How to get the testCafe exit code
But still my problem remains.
I've toyed around with my argv.json file.
I've toyed around with my CICDtestBranches.json file.
I've toyed around with my package.json file.
I've tested the same branch that has the problem on multiple
machines.
I've tested with multiple browsers (Firefox & Chrome) -
both produce the same problem.
I've tried to re-arrange the code, see
below
I've tried add multiple tests in a fixture and added a page
navigation to each one.
I've tried to remove code that is processing
irrelevant options like video logs & concurrency (parallel execution)
I also talked with some coworkers around the office who have done similar projects and asked them what they did to fix the problem. I tried their recommendations, and even re-arranging things according to what they tried and still no joy.
I've read through the TestCafe documentation on how to implement a test runner several times and still I haven't been able to find any specific information about how to solve a problem with the browser not closing at the end of the test/fixture/script run.
I did find a few bugs that describe similar behavior, but all of those bugs have been fixed and the remaining bugs are specific to either Firefox or Safari. In my case the problem is with both Chrome & Firefox. I am running TestCafe 1.4.2. I don't want to file a bug with TestCafe unless it really is a confirmed bug and there is nothing else that can be done to solve it.
So I know others have had this same problem since my coworker said he faced the same problem with his implementation.
Since I know I am out of options at this point, I'm posting the question here in the hopes that someone will have a solution. Thank you for taking the time to look over my problem.
When executing the below code, after the return returnData; is executed, the .then statement is never executed so the TestCafe command and browser window are never terminated.
FYI the following code is CommonJS implemented with pure NodeJS NOT ES6 since this is the code that starts TestCafe (app.js) and not the script code.
...**Boiler Plate testcafe.createRunner() Code**...
console.log('Starting test');
var returnData = tcRunner.run(runOptions);
console.log('Done running tests');
return returnData;
})
.then(failed => {
console.log(`Test finished with ${failed} failures`);
exitCode = failed;
if (argv.upload) return upload(jsonReporterName);
else return 0;
testcafe.close();
process.exit(exitCode);
})
.then(() => {
console.log('Killing TestCafe');
testcafe.close();
process.exit(exitCode);
});
I've tried to swap around the two final .then statements to try and see if having one before the other will cause it to close. I copied the testcafe.close() and process.exit() and put them after the if-else statement in the then-failed block, although I know they might-should not get called because of the if-else return statements just before that.
I've tried moving those close and exit statements before the if-else returns just to see if that might solve it.
I know there are a lot of other factors that could play into this scenario, like I said I played around with the runOptions:
const runOptions = {
// Testcafe run options, see: https://devexpress.github.io/testcafe/documentation/using-testcafe/programming-interface/runner.html#run
skipJSErrors: true,
quarantineMode: true,
selectorTimeout: 50000,
assertionTimeout: 7000,
speed: 0.01
};
Best way I can say to access this problem and project and all of the code would be to clone the git lab repo:
> git clone "https://github.com/SethEden/CAFfeinated.git"
Then checkout the branch that I have been working this problem with: master
You will need to create an environment variable on your system to tell the framework what sub-path it should work with for the test site configuration system.
CAFFEINATED_TEST_SITE_NAME value: SethEden
You'll need to do a few other commands:
> npm install
> npm link
Then execute the command to run all the tests (just 1 for now)
> CAFfeinated
The output should look something like this:
$ CAFfeinated
Starting test
Done running tests
Running tests in:
- Chrome 76.0.3809 / Windows 10.0.0
LodPage
Got into the setup Test
Got to the end of the test1, see if it gets here and then the test is still running?
√ LodPage
At this point the browser will still be spinning, and the command line is still busy. You can see from the console output above that the "Done running tests" console log has been output and the test/fixture should be done since the "Got to the end of the test1,..." console log has also been executed, that is run as part of the test.after(...). So the next thing to execute should be in the app.js with the .then(()) call.....but it's not. What gives? Any ideas?
I'm looking for what specifically will solve this problem, not just so that I can solve it, but so others don't run into the same pitfall in the future. There must be some magic sauce that I am missing that is probably very obvious to others, but not so obvious to me or others who are relatively new to JavaScript & NodeJS & ES6 & TestCafe.
The problem occurs because you specified the wrong value for the runner.src() method.
The cause of the issue is in your custom reporter. I removed your reporter and now it works correctly. Please try this approach and recheck your reporter.

PDF.js HTA, promise being rejected

I'm trying to develop an HTA for extracting and processing the data from PDF files for a number of people in a large office. I've been looking into using the PDF.js package for this, but I've not been able to get it working.
I've forked the project and created an HTA version of the helloworld example with the compatibility.js file included. I can get an HTML version of this working on Firefox and IE11 through a gulp server, but the HTA doesn't give any output - no text, no error messages.
After peppering the source files with alert() statements, I've discovered that the original hello.js file is missing promise reject function, and that this fires when added, but here where my I meet the limits of my knowledge. I don't really know an awful lot about promises, so I don't understand why this one fails. Is this solvable or does it mean that the package simply won't run in an HTA?
EDIT:
I've been looking more into this and the failure doesn't make sense.
Tracing the logic through, the hello.js file calls the function api.getDocument from api.js. Following this back, there is only one return statement and the alert statement just before this line is running. However the fulfilled function is not triggering.
From my very limited understanding, the failure clause on a promise will be triggered from a throw() statement within the asynchronous operation. If that is the case then I would expect that operation to immediately cease and the reject function to trigger, but why would the line immediately before the return statement still run?
I did pursue one theory that this line from api.js was the one throwing the error:
}).catch(task._capability.reject);
To check this, I added an alert statement to the reject() function statement in util.js, but it did not trigger, so I can't tell where the error is coming from.
Is anyone able to give me any additional pointers to help me trace this down?
Solved!
By changing the compatibility setting to IE10 instead of IE9 (which I didn't know I could do) I got a more useful error in the right place. Looking more into this, this issue appears to be a duplicate of this one:
Access denied in IE 10 and 11 when ajax target is localhost

Correct usage of process.exit in NodeJS

I'd like to start off by saying that I'm a complete NodeJS noobie.
So, that being said, I'm trying to get a better understanding of the behavior of parent and child processes when using the Cluster API of NodeJS along with process.exit. I also realize that all of these doubts relate to the behavior of Unix itself.
I know that process.exit() causes the current process to exit with the "success" code, 0.
For my test, I have 2 files: index.js and indexWorker.js.
Here's what index.js looks like:
var cluster = require('cluster');
if (cluster.isMaster) {
// Setup the required fork behavior.
cluster.setupMaster({
exec: 'indexWorker.js'
});
var cpuCount = require('os').cpus().length;
// Create a worker for each logical core.
for (var i = 0; i < cpuCount; ++i) {
cluster.fork({'NODE_ENV': 'development'});
}
console.log('Calling process.exit on parent.');
process.exit();
}
And here's what indexWorker.js looks like:
var cluster = require('cluster');
console.log("Started worker having ID: " + cluster.worker.id);
Here are my questions/doubts:
Doubt 1
Now, since I'm using process.exit on the parent, my understanding is that all the worker process ought to become orphan process. However, firstly, the control doesn't return to my terminal window until I do a ^C, despite the fact that the parent (index.js) is exiting right away. Also, ps, ps -ax, ps -elf | grep <pattern> don't seem to think that there are any node programs running.
So my doubt is: why isn't the control returning to the terminal and why isn't ps showing me anything?
Doubt 2
If I remove process.exit from index.js, my understanding is that the control doesn't return to my terminal because despite the parent having finished it's task, the child processes are running and thus the parent hasn't exited. Is that a correct understanding or am I missing something?
Doubt 3
If I remove the cluster.fork call and process.exit() call from index.js, the script completes and returns control to my terminal window immediately, as index.js isn't doing much in that case.
However, as you can see, indexWorker.js isn't doing any long operations either. It's simply printing a console message. Why, in that case, are the processes still running? Shouldn't the behavior be the same as the parent's, i.e. exit on script completion and thereby eventually return control to the terminal window?
I've simply been running node index.js for all these tests; never putting any processes in the background. My tests are being run on a Mac.
That's all the doubts I have, for now. :)
I've basically been experimenting by putting process.exit in different places and running ps, hence my doubts around these points. If there are any more things that you'd like to point out regarding the parent/child process behavior that aren't covered in my doubts, I'd greatly appreciate it! It'll definitely help me and the community in some way.
So, thanks in advance to the SO community!
Cheers!

Categories