I'm new to Node.js but I wanted to use it as a quick web server which would simply take in a request uri and then run a query on an internal service which returns a JSON stream.
I.e. something like this:
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
if(uri === "/streamA") {
//send get request to internal network server http://server:1234/db?someReqA -->Returns JSON ....?
//send response to requestor of the JSON from the above get ....?
}
else if(uri === "/streamB") {
//send get request to internal network server http://server:1234/db?someReqB -->Returns JSON ....?
//send response to requestor of the JSON from the above get....?
}.listen(8080);
I'm using the newest stable version of node.js - version 0.4.12. I was hoping this would be very easy to do however, I havent been able to find some examples on the net as they all seem to use an old API version so I'm getting error after error.
Would anyone be able to provide a code solution to the above that works with the new Node APIs?
Thanks!
JSON is one of the most common types of data you'll work with in Node, and being able to read and write JSON files is very useful. You've learned how to use fs. readFile and fs. writeFile to asynchronously work with the filesystem, as well as how to parse data to and from JSON format, and catch errors from JSON.
Update: Since Node. js 17. 5 , it's possible to leverage import assertions in ECMAScript modules to import JSON files. /* Experimental JSON import is supported since Node.
here is a code that should explain your task:
var http = require('http');
var url = require('url')
var options = {
host: 'www.google.com',
port: 80,
path: '/' //Make sure path is escaped
}; //Options for getting the remote page
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
if(uri === "/streamA") {
http.get(options, function(res) {
res.pipe( response ); //Everything from the remote page is written into the response
//The connection is also auto closed
}).on('error', function(e) {
response.writeHead( 500 ); //Internal server error
response.end( "Got error " + e); //End the request with this message
});
} else {
response.writeHead( 404 ); //Could not find it
response.end("Invalid request");
}
}).listen(8080);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With