I'm having a weird problem with child process in node.js I have some code running in a child process like this, but the child process exits with code 0 in between lines of synchronous code.
var fs = require('fs');
var http = require('http');
var mkdirp = require('mkdirp');
var urlPath = __dirname + "\\urls.txt";
var savePath = __dirname + "\\";
var objects = [];
var globalI = 0;
var file;
if (!fs.existsSync(urlPath))
{
console.log("File at " + urlPath + " does not exist!");
}
else
{
if(!fs.existsSync(savePath)){
mkdirp.sync(savePath);
}
console.log("File found! Reading...");
console.log("still running");
try{
var data = fs.readFileSync(urlPath, {"encoding":"utf8"});
} catch (err) {
console.log("Error reading url file...");
throw err;
} finally {
console.log("File read!");
var array = data.split("\n");
console.log("Found " + array.length + " urls");
}
The line
console.log("File found! Reading...");
Runs and appears in the console. However the next line
console.log("still running");
does not run. The child process exits before that line of code. I have absolutely no idea why. Any insight would be tremendously appreciated!
Also, if I change the order of the two statements, it still only executes the first before exiting.
EDIT
So maybe it does have to do with flushing and that other bug. If I remove both of those consecutive log statements, it runs the next log statement in the finally
block and then quits.
EDIT2
There is also something else curious about this problem. You can see in the code snippet I have a variable called globalI
Later on in the code, that variable gets incremented simply like globalI++;
If I uncomment the incrementation, the child process stops exiting unexpectedly But it makes no sense, because it never even comes close to the line where the incrementation happens when it does exit unexpectedly.
That is actually how I started having this problem. I am completely flabbergasted
You are missing a } after finally, but I very seriously doubt that has anything to do with it and was probably just a copy past error.
It looks to me like you might possibly be exiting the program before stdout can be flushed. There used to be a flush call you could explicitly make in older node versions, but not anymore.
Read this thread where people are having very similar issues to yours:
https://github.com/joyent/node/issues/1669
This seems hard to believe based on the fact you are doing a readFileSync call after that, but I suppose it's still possible.
One thing you could do to test it is to simply set a timeout before both your writes for something ridiculous like 5 seconds. This will keep the program alive for 5 seconds, more than enough time for any console logs to get flushed out.
If both lines make it out, then you know you have a timing issue. If it's still busted after that at least you can eliminate timing as an issue.
Maybe you are somehow getting an unhandled error. You can put the following code in and see if it gets triggered: