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
Related
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.
I am new to nodeJS. I am trying to load an index.html page onto my 8080 port and have this:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
function home(req, res) {
if(req.url == '/'){
fs.readFile('index.html', function read (err, data) {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(data);
res.end();
});
}
};
var server = http.createServer(function (req, res) {
home(req, res);
});
server.listen(PORT);
I have 3 files in the same directory: index.html, style.css, server.js. I start up the server and the page will not load until after I hit cntrl + c. Why is this?
You have written the data to the response, but you have not finished the response. Put res.end(); after your res.write function.
Without this, the browser keeps waiting for more data from the server. When you shut down the server with Ctrl-C, the server closes the connection, and the browser renders what it received.
If you are new to Node, I would recommend looking into something like Express, which handles a lot of important things like routing (what URLs go to which pages) for you and will save you a lot more if statements in the future.
I have server.js and client.html.
Server.js is running on nodejs and is simply:
var http = require('http'), fs = require('fs');
var app = http.createServer(function(request, response) {
fs.readFile("client.html", 'utf-8', function(error, data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
});
}).listen(80);
and then I have client.html which is also very simply just
<img src="/public/images/avatar.gif">
Which just displays as though the image is not valid, I have checked the the director over and over and it is fine, why would it be doing this? I thought it might be because of the headers but text/html should surely display images?
Regards
Matt
It's not displaying the image because for every request (including the image request) it's returning the contents of clients.html.
If you want a static file server, i suggest looking at connect: http://www.senchalabs.org/connect/ or for something simpler, have a look at this: https://gist.github.com/rpflorence/701407
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.
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.