Node.js how to keep on reading a text file - javascript

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.

Related

How do I use Node functions and variables from HTML while using a server?

I'm trying to build a few programs that execute Node.js functions from HTML (e.g you press a button and some code using Node.js runs).
Here is the code I'm using to display the HTML
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
(Too long for a comment.)
First you must decide whether pressing a button shall
lead to a complete new HTML page that contains the results of the Node.js code execution or
update only parts of your existing HTML page.
In the first case, sending back static HTML pages (as your code does) will not be sufficient, you would need a template engine.
In the second case, you need client-side Javascript code to fetch JSON data (say) from your server and update the DOM of your HTML page.

Can't serve javascript file with html - node.js

I have a webpage with an HTML, CSS, and JS file. It also has one image. I am able to get all of them to function and serve onto the client side, except for the javascript portion. It is most likely a silly syntax thing but I have not been able to solve it.
Here is the code for my .js serving:
else if(req.url === '/index.js'){
console.log("SERVING JS")
res.writeHead(200, {'Content-Type': 'application/json'})
var javaContents = fs.readFileSync('./public/index.js', {encoding: 'UTF8'});
res.write(javaContents);
res.end();
}
^^^ Which is inside my requestHandler function:
function requestHandler(req, res){
}
Before this, I also have:
var http = require('http'), fs = require('fs');
var fs = require('fs');
And I declare my server variable last:
var server = http.createServer(requestHandler);
server.listen(9934, function(){
console.log("== Server is listening on port 9934");
});
I could post all my code but I think that is not necessary. Thank you!

Node.js page not loading when refreshed

I want to create a simple Node.js server and send data with pipe() method. But I have an issue.
The page loads when server started the first time, but when I refresh the page, it becomes blank. I mean the data is not loaded. Why does it happen?
var http = require('http'),
fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
myReadStream.pipe(res);
}).listen(3300);
This would work if you change it to:
http.createServer(function (req, res) {
var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
res.writeHead(200, {'Content-Type': 'text/plain'});
myReadStream.pipe(res);
}).listen(3300);
That's because the stream once read is not rewinded automatically (in fact it cannot be).
But it's not the most flexible way to serve static content.
See this answer for five examples of serving static files with and without Express, from using high-level frameworks to very low level manual reinventing the wheel kind of implementation.
How to serve an image using nodejs

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).

Setting a document root to your Node.js http server?

I just setup a basic node.js server with socket.io on my local machine. Is there a way to set a document root so that you can include other files. Ie. Below I have a DIV with a a background image. The path the image is relative to the location of the server, however this is not working. Any ideas? Thanks!
var http = require('http'),
io = require('socket.io'), // for npm, otherwise use require('./path/to/socket.io')
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<div style="background-image:url(img/carbon_fibre.gif);"><h1>Hello world</h1></div>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
Use Express or Connect. Examples: https://github.com/spadin/simple-express-static-server, http://senchalabs.github.com/connect/middleware-static.html
For the background-image style, browser will create a entirely new HTTP Request to your server with path *img/carbon_fibre.gif*, and this request will certainly hit your anonymous function, but your response function only write back a div with ContentType: text/html regardless the req.pathname so that the image cannot be properly displayed.
You may add some code to your function like:
var http = require('http'),
io = require('socket.io'),
fs = require('fs'),
server = http.createServer(function(req, res){
// find static image file
if (/\.gif$/.test(req.pathname)) {
fs.read(req.pathname, function(err, data) {
res.writeHead(200, { 'Content-Type': 'image/gif' });
res.end(data);
});
}
else {
// write your div
}
});
server.listen(8080);
I'm not very familiar with nodejs, so the code above only demonstrates a logic but not the actual runnable code block.

Categories

Resources