Alternative to waiting for child_process to quit node.js - node.js

I've got these 2 codes running in 1 script:
The ping script:
app.get("/ping", function(req, res) {
res.send("Pong!");
});
And a work in progress youtube downloader:
app.post("/nodedl", function(req, res) {
res.write("===Gradyncore listnener===\n")
res.write("Recived POST request from "+req.ip+" to /nodedl\n")
res.write("POST(url): "+req.body.url+"\n")
res.write("checking key...\n")
if (req.body.key==="<Insert key here>"){
res.write("Key is valid! Skipping pre-download script...\n")
} else {
res.write("Key is invalid. Running pre-download script...\n")
exec("/home/gradyn/website/projects/nodeDL/scripts/check.sh", function (error, results) {
if (results != null) {
res.write(results+"\n");
} else if (error != null) {
res.write("Error: " + error+"\n");
}
});
}
res.end();
});
The problem is, by the time check.sh finishes, res.end(); has allredy been emitted, causing this error followed by a crash
events.js:160
throw er; // Unhandled 'error' event
^
Error: write after end
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:439:15)
at /home/gradyn/listener/app.js:29:13
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
I'm fairly new to node.js, but from what I understand, If i wait for the child process to complete before calling res.end(), the entire script (including the ping listener) will not work until the child process completes.
How should I go about doing this?

Problem is that your exec is asynchronous, code below it won't wait to for completion of exec and get executed... You have to end response inside callback function:
app.post("/nodedl", function(req, res) {
res.write("===Gradyncore listnener===\n")
res.write("Recived POST request from "+req.ip+" to /nodedl\n")
res.write("POST(url): "+req.body.url+"\n")
res.write("checking key...\n")
if (req.body.key==="<Insert key here>"){
res.write("Key is valid! Skipping pre-download script...\n")
} else {
res.write("Key is invalid. Running pre-download script...\n")
exec("/home/gradyn/website/projects/nodeDL/scripts/check.sh", function(error, results) {
if (results != null) {
res.write(results+"\n");
res.end();
} else if (error != null) {
res.write("Error: " + error+"\n");
res.end();
}
});
}
});

Related

node reciving an unhandled error event need some insite?

I've searched Hi and Low through web sites and docs, and I've yet to figure out why Im getting this error. Yes I'm new to node. I thought id ask here as a last resort.
the error I'm receiving is:
events.js:292
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:668:15)
at ServerResponse.end (_http_outgoing.js:789:7)
at Server.<anonymous> (/mnt/sdc/opt/codeWork/ReactBuilds/be_full-stack/app.js:10:9)
at Server.emit (events.js:315:20)
at parserOnIncoming (_http_server.js:874:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:727:7)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
Here's my code I'm running node v14.16.0
const http = require('http')
const server = http.createServer((req, res)=>{
if(req.url === '/') {
res.end('Welcome to our home page')
}
if(req.url === '/about') {
res.end('Here is our short history')
}
res.end(`
<h1>Ooops</h1>
<p>This is not the page you are looking for</p>
backHome
`)
})
server.listen(5000)
any incites are very welcome
Thanks
You should introduce early returns in your code so that you don't call res.end multiple times when one of the conditions evaluates to true with your request handler still handling 404:
const server = http.createServer((req, res) => {
if (req.url === "/") {
return res.end("Welcome to our home page");
}
if (req.url === "/about") {
return res.end("Here is our short history");
}
res.end(`
<h1>Ooops</h1>
<p>This is not the page you are looking for</p>
backHome
`);
});

What I need for the callback parameter for returnCharData function?

N need some help here using this API.
I'm trying to get data from Poloniex API for NodeJS (npm Install)
I'm confuse with which parameter i have to pass here in the callback parameter, I'm new in nodeJS, so maybe im getting wrong what i need as a callback.
This method is used for the API to fetch data from the poloneix web, to calculate basic things, currently i need the information of the Pair BTC/USD, here is the property of the poloneix instance:
returnChartData(currencyA, currencyB, period, start, end, callback);
It is Declared as this in the poloneix.js file:
returnChartData: function(currencyA, currencyB, period, start, end, callback) {
var parameters = {
currencyPair: joinCurrencies(currencyA, currencyB),
period: period,
start: start,
end: end
};
What do I need to use in as a callback parameter for this Function?
var response = poloniex.returnChartData('BTC','LTC',300,1510570525,1510638955,**(¿here?)**)
fs.appendFile('BTC_pair.json', response, function(err) {
if(err) {
console.log('there was an error: ', err);
return;
}
console.log('BTC Pair Saved');
});
I know it is Wrong, but i tried to use simple Fucntions, for example as a Timer to explore what i need to pass as a callback, and im getting this error while running executing my node file:
D:\Projects\NodeJS\ZenBot\ZenBot_v2\poloniex.js\lib\poloniex.js:79
callback(err, body);
^
TypeError: callback is not a function
at Request._callback (D:\Projects\NodeJS\ZenBot\ZenBot_v2\poloniex.js\lib\poloniex.js:79:7)
at Request.self.callback (D:\Projects\NodeJS\ZenBot\ZenBot_v2\poloniex.js\node_modules\request\request.js:122:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:194:7)
at Request.<anonymous> (D:\Projects\NodeJS\ZenBot\ZenBot_v2\poloniex.js\node_modules\request\request.js:888:14)
at emitOne (events.js:101:20)
at Request.emit (events.js:191:7)
at IncomingMessage.<anonymous> (D:\Projects\NodeJS\ZenBot\ZenBot_v2\poloniex.js\node_modules\request\request.js:839:
12)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
And in the poloniex.js File here in the constructor is where the error is comming:
_request: function(options, callback) {
if (!('headers' in options)) {
options.headers = {};
}
options.json = true;
options.headers['User-Agent'] = Poloniex.USER_AGENT;
options.strictSSL = Poloniex.STRICT_SSL;
request(options, function(err, response, body) {
// Empty response
if (!err && (typeof body === 'undefined' || body === null)){
err = 'Empty response';
}
callback(err, body); <----- THIS LINE
});
Do I need to declare any function? or something?

Node server is getting down with Error: write after end

We are streaming files from s3, its running well but sometime (randomly in few days) its gives error and node instance is getting down. our code is
s3Utils.headObject(assetId, function (err, metadata) {
if (err && err.code === 'NotFound') {
console.log("file not found on s3: ", assetId) ;
res.send({"success":false, "message":"file not found on s3: "+ assetId});
} else {
var download_file_name = assetId;
if(metadata.Metadata && metadata.Metadata.filename) {
download_file_name = metadata.Metadata.filename;
}
if(metadata.ContentLength) {
res.setHeader('Content-Length',metadata.ContentLength);
}
res.setHeader('Content-disposition', 'attachment; filename=' +download_file_name);
res.attachment(download_file_name);
var fileStream = s3Utils.getObjectAsReadStream(assetId);
fileStream.pipe(res);
}
});
we are getting below error in logs
events.js:154
throw er; // Unhandled 'error' event
^
Error: write after end
at writeAfterEnd (_stream_writable.js:166:12)
at PassThrough.Writable.write (_stream_writable.js:211:5)
at IncomingMessage.ondata (_stream_readable.js:536:20)
at emitOne (events.js:90:13)
at IncomingMessage.emit (events.js:182:7)
at IncomingMessage.Readable.read (_stream_readable.js:368:10)
at flow (_stream_readable.js:751:26)
at resume_ (_stream_readable.js:731:3)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
Server is getting down after this error.
Please suggest.

Connection ended and command aborted in a script

I try to make a little script with node.js (v6.5.0). The first part of this script displays a word randomly found in a list. Then it uses the word (as the key) the display its value (the translation). The script requires the node-redis module. The problem I get seems related to the asynchronous nature of the functions. Is it because the first function is asynchronous that I can't reuse the argument in the nested one? I'm stucked and some directions would be really appreciated.
Here's a snippet of the code...
var redis = require('redis');
var fs = require('fs');
var client = redis.createClient();
client.on('connect', function() {
});
client.randomkey(function (err, word) {
console.log('The question is: ' + word);
client.get('word', function(err, reply) {
if (err) {
console.log(err);
}
//otherwise show the value of this key.
});
});
client.quit();
... and this the error message I get when launching the command node drill.js
The question is: chicken
{ AbortError: Stream connection ended and command aborted. It might have been processed.
at RedisClient.flush_and_error (...thesaurus/node_modules/redis/index.js:350:23)
at RedisClient.connection_gone (...thesaurus/node_modules/redis/index.js:585:14)
at Socket.<anonymous>
(...thesaurus/node_modules/redis/index.js:282:14)
at Socket.g (events.js:286:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at TCP._handle.close [as _onclose] (net.js:493:12) code: 'NR_CLOSED', command: 'GET', args: [ 'word' ] }
You should call the inner function with the variable, not a string. It will not work like that.
client.randomkey(function (err, word) {
console.log('The question is: ' + word);
client.get(word, function(err, reply) {
if (err) {
console.log(err);
} else {
console.log(reply);
}
// put quiting of the client here NOT at the end of your document
client.quit();
});
});
And then you didn't output the result of the second query.
EDIT: And of course you can't close the connection the way you do, as you would close the connection before the inner function is finished.

throw new RangeError node js

I'm trying to work with IBM Watson Conversation service with Node.js.
I use 'express' to post a message:
app.post( '/api/message', function(req, res) {
}
and to print the message got from the service:
conversation.message( payload, function(err, data) {
if ( err ) {
return res.status( err.code || 500 ).json( err );
}
return res.json( updateMessage( payload, data ) );
} );
I just ran the application on port 3000. While the page is not loaded and I got this error:
_http_server.js:192
throw new RangeError(`Invalid status code: ${statusCode}`);
^
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:573:10)
at ServerResponse.send (C:\IBM\1.Mission\2016\conversation-simple-master(1)\
conversation-simple-master\node_modules\express\lib\response.js:204:10)
at ServerResponse.json (C:\IBM\1.Mission\2016\conversation-simple-master(1)\
conversation-simple-master\node_modules\express\lib\response.js:249:15)
at C:\IBM\1.Mission\2016\conversation-simple-master(1)\conversation-simple-m
aster\app.js:86:44
at Request._callback (C:\IBM\1.Mission\2016\conversation-simple-master(1)\co
nversation-simple-master\node_modules\watson-developer-cloud\lib\requestwrapper.
js:47:7)
at self.callback (C:\IBM\1.Mission\2016\conversation-simple-master(1)\conver
sation-simple-master\node_modules\watson-developer-cloud\node_modules\request\re
quest.js:200:22)
at emitOne (events.js:77:13)
at Request.emit (events.js:169:7)
I don't think the problem is from npm, back my package... While it seems a generic problem...Thanks for you help.
Request to IBM Watson Conversation service probably ended with error with code "0" and it isn't a valid HTTP status code. This should work:
conversation.message(payload, function(err, data) {
if (err) {
return res.status(500).json(err);
}
return res.json(updateMessage(payload, data));
});

Resources