Node js | Use external file to send as response? - javascript

I saw a similar question, but I'm looking for a way to do it manually. I don't want to use express or another library to do it.
var http = require('http');
var server = http.createServer(function(req, res) {
res.end('<h1 >Hi!</h1>'); //I want to to fetch a file ex: index.html
});
server.listen(9334);
How would i do that? Also as a sub-question, just because I'm curious. Is it possible to use jQuery ajax to fetch this file?

Here is one way to do is using 'fs'.
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.createReadStream("filename.ext").pipe(res);
});
server.listen(9334);
This is also good because if the file is big the data is streamed to the response instead of waiting for the read operation to be completed. Although you might have to set 'Content-Type' header in some cases.

Related

Node.js - piping a readable stream to http response

I am doing node.js exercises from nodeschool.io (learnyounode). One of the exercises involves creating a http server which serves a text file from a readable file stream. I'm very new to asynchronous programming. The solution I came up with is:
var http = require('http');
var fs = require('fs');
var readable = fs.createReadStream(process.argv[3]);
var server = http.createServer(function(request, response) {
readable.on('data', function(chunk) {
response.write(chunk);
})
});
server.listen(process.argv[2]);
This works, however the official solution uses a pipe instead of on-data event:
var http = require('http')
var fs = require('fs')
var server = http.createServer(function (req, res) {
res.writeHead(200, { 'content-type': 'text/plain' })
fs.createReadStream(process.argv[3]).pipe(res);
})
server.listen(Number(process.argv[2]))
What are the (potential) differences and/or benefits of doing it either way?
Well, there's more code in your version, and that usually means you have more options to make mistakes. Take into account some edge cases, like what happens when the stream throws an error?
I'm not exactly sure what the behavior would be (you can check yourself by e.g. inserting some non-existing filename) but chances are that in your version the error handling is not working very well, potentially ignoring errors (because you're not listening for error events).

In Node JS, how do i create an endpoint pass through? I'm using express and http

In Node JS, how do i create an endpoint pass through?
I'm using express and http
The entire app will be a just a series of pass through endpoints.
Here is my code
// the real endpoint is somewhere else.
// for example http://m-engine.herokuapp.com/api/getstudents2
var http = require('http');
var options = {
host: 'http://m-engine.herokuapp.com',
path: '/api/getstudents2',
method: 'GET'
};
app.get('/api/getstudents', function(req, res){
// now past the request through
http.request(options, function(response2) {
response2.on('data', function (data) {
res.json(data);
});
}).end();
});
You can make use bouncy or node-http-proxy module for node.js to achieve the same thing.
Here is the sample code for bouncy:
var fs = require('fs');
var crypto = require('crypto');
var bouncy = require('bouncy');
bouncy(function (req, bounce) {
bounce("http://m-engine.herokuapp.com");
}).listen(8000);
Although, you can achieve the same thing with help of nginx also. No need to create node service for the same thing. Search on google for nginx proxy_pass. You can get examples for the same.

Nodejs, expressjs - how to serve delayed response

I am building a webservice, for which i am using nodejs, phantomjs and expressjs. I am learning all the three.
I want to serve a delayed response to the clients after processing their query. Like for example,
I am processing certain inputs from my client, then, i want to process the data at the backend which will take approx 10 sec on an avg. Then i wanted to serve this page to the client.
Is it possible in node to send multiple responses to the same request or delayed responses so that the template will automatically update the contents.
Or , should i use the same method , like store the json in a file in the server , then serve the page with ajax which will query the page.
please help me. here is the code which i wrote ,
app-server.js(the main file):
// import express module
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// define all required template files to be served and also define the template engine
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
// Useful modules
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// import the routes
require('./router')(app);
app.listen(8080);
router.js:
var crypto = require('crypto');
var express = require('express');
module.exports = function (app) {
// define the static routes.
app.use('/static', express.static('./static'));
app.use('/media', express.static('./media'));
//defining the controller.
var parserlib = require('./controller.js')
// Define the home root path
app.get('/', function (req, res) {
// shows the home search page.
res.render('index', {content:'template success'});
});
app.get('/search', function(req, res){
res.redirect('/');
});
app.post('/search', parserlib.parserlib);
}
controller.js:
var crypto = require('crypto');
var path = require('path')
var childProcess = require('child_process')
exports.parserlib= function(req, res){
var output = '';
var url = req.body.search_url;
var childArgs = [
path.join(__dirname, 'external-script.js'),
url,
]
// execute the script in a separate thread.
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
// handle results
console.log(stdout);
output = stdout;
//console.log(err);
//res.send(output);
});
//res.send(output);
};
so , what i want to see is, first send a response to client stating that its loading, then i want to update the with processed data. In other languages its not possible to send multiple responses. Not sure about nodejs.
Also, do i have to store the json output from the processed lib to a file and then use ajax to query ? or is it possible to directly update the json object to the client ?
Thanks
This is just not how HTTP works. The clients won't expect it. This has nothing to do with Node or any other framework. The way to do what you're attempting is to actually send a response that the thing is loading, and then have some other mechanism for reporting state.
As an example, you might design a RESTful API. In that RESTful API you might define a endpoint for creating new things:
POST /api/things
The client would post data to that to create a new thing. The response should be something that provides a location of the newly created resource, for example an HTTP 301 to /api/things/1.
If the user goes to /api/things/1 and the thing isn't done getting made yet, then you can either do a temporary redirect (303) to /api/things/1/status which provides some helpful status information, or just issue a 404.
If you actually want to send back server-side pushes of status information, then you should be looking at WebSockets or a pure Socket API of some kind, neither of which is provided by Express, but both of which are available in Node (checkout the socket.io library and the net core library)

Nodejs/Expressjs javascript: get where request came from

I am using nodejs with the expressjs module to create a webserver.
My current setup is this
var express = require("C:/Program Files/nodejs/node_modules/express")
var app = express();
var server = require('http').createServer(app).listen(80);
var io = require('C:/Program Files/nodejs/node_modules/socket.io').listen(server, {log:false});
var path = require("path");
fs = require("fs");
is there a way using
app.use(function(req,res,next){
//code
})
to get where a request came from? Eg, if on an html page, you have the script tag
<script src="test.js"></script>
it sends a request to retrieve test.js, can I use the req argument to see that the request for test.js came from the html page and get the full filepath of the html page?
EDIT: I'm trying to write a function that serves the correct index file (index.html/.htm/.php etc if you just enter a directory into the url ("localhost/tests/chat/"), but the problem then is, when it requests the javascript file from the index page, it goes back 1 directory too far (searches for "localhost/tests/test.js" instead of "localhost/tests/chat/test.js"), and only works if you directly type the filename into the url ("localhost/tests/chat/index.html").
My function:
app.use(function(req,res,next){
var getFullPath = path.join("public",req.path);
console.log(req.path);
if (fs.existsSync(getFullPath)) {
if (fs.statSync(getFullPath).isDirectory()) {
getFullPath = path.join(getFullPath,"index.html");
}
res.sendfile(getFullPath);
} else {
res.send("404 Not Found");
}
});
I realise you can use
app.use(express.static(__dirname + '/public'));
but this creates a problem for me with my custom php parser module so that's not really an option
I was able to use req.headers.referer to get where the javascript file was being asked from and therefore point to the correct location of the javascript file.
getFullPath = path.join("public",req.headers.referer.split(req.host)[1],path.basename(req.path));

Node.js how to keep on reading a text file

I'm trying to read a text file. The text file is updated everytime an event occurs in my c program in linux.
Here's my code.
var http = require('http'),
fs = require('fs');
var filetoread = fs.readFileSync('this_is_a_log.txt');
server = http.createServer();
server.on('request', function(req, res){
res.writeHead(200, {'content-type': 'text/html'});
res.end(filetoread);
});
server.listen(9000);
How can node.js continue reading the text file so the page keeps updated everytime the text file is modified. I don't want to use a delay or timeout, I want to do it real time. Is there a function in node.js that can do this. Also I don't want to use tail.

Categories

Resources