Okay so basically I am building an application for JavaScript development using Node. My issue that keeps arising is when the server starts.
var host = '127.0.0.1',
port = 8080;
var fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var buffer = new Buffer(100);
res.end(fs.read('index.html'));
}).listen(port, host);
console.log('Server running at http://' + host + ':' + port);
My issue lies with res.end(fs.read('index.html')); I want the server to run that html document when a connection is made in the browser. I always get this error response in the console.
buffer.js:236
throw new Error('First argument needs to be a number, ' +
Error: First argument needs to be a number, array or string.
at new Buffer (buffer.js:236:15)
at Object.fs.read (fs.js:348:14)
at Server.<anonymous> (C:\Users\myname\Desktop\app\bin\server.js:45:20)
at Sever.EventEmitter.emit (events.js:96:17)
at HTTPParser.parser.onIncoming (http.js:1807:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
at Socket.socket.ondata (http.js:1704:22)
My question is, how do you display an html document in the web browser when a connection is made to the server? Any help is appreciated. Thanks.
Your code raises a few questions but if I understand your requirement this is what you need:
You need to write the result of the file to the response stream as you see below.
var host = '127.0.0.1',
port = 8080;
var fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html',function(err,data){
res.write(data);
res.end();
});
}).listen(port, host);
console.log('Server running at http://' + host + ':' + port);
Of course this has no error checking etc but will get you going.