Ok, I'm new to Node.js so excuse the noob question. Heres my simple code:
var http = require('http');
var fs = require('fs');
// simple node.js server
server = http.createServer(function (request, response){
var get_text = function (errors, contents){
response.write(contents);
response.end('hello world');
}
// get_text is the callback
fs.readFile('log.txt', get_text);
response.write('End of the callback');
response.writeHead(200);
});
server.listen(8000);
console.log('Server running at port 8000');
As it stands, when I run the script in my terminal it will start the server properly but when I go to my localhost:8000 in my browser (chrome) it comes up as "webpage not available".
If I comment out the writeHead command it works fine.
Why?
This is because you're attempting to .writeHead() after .write():
response.write('End of the callback');
response.writeHead(200);
.writeHead() has to be first:
response.writeHead(200);
response.write('End of the callback\n');
Related
I want to build a MQTT Broker in Typescript with angular. I have tried some examples, but always get the error:
Uncaught TypeError: http.createServer is not a function
Here the simple example i am trying to run at the moment:
var http = require('http');
var port2 = 9000;
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello there, world\n');
}).listen(port2);
console.log("Listening on port " + port2);
Has anyone an idea where i get this error from, or an other example broker I could try?
Thank you for your help!
Your code is probably being run in the browser while using Node.js APIs.
A Node error would look like this:
While a browser error looks more similar to what you refer to in the question.
The snippet I've run for both of these tests is as follows:
var http = {};
var port2 = 9000;
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello there, world\n');
}).listen(port2);
console.log("Listening on port " + port2);
Your provided snippet works OK when run on the latest Nodejs docker image with node.
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'm tring to read this file in nodejs using fs module.
I'm getting the response twice. let me know what am i doing wrong. Here's my code.
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res) {
fs.readFile('sample.txt', function(err, sampleData) {
console.log(String(sampleData));
//res.end();
});
console.log("The end");
// res.writeHead(200);
res.end();
}).listen(2000);
After hitting the port in browser. I'm getting the response twice in my terminal. Here's the output.
The end
this is sample text for the testing.
The end
this is sample text for the testing.
You are most likely getting it twice because you are accessing http://localhost:2000/ from the browser.
When doing so there are actually two requests being made. Your actual request and the favicon :) both of which are handled by your server.
Have a look into Chrome debugger -> Network
Two log messages will appear: one for / and one for /favicon.ico
You can verify this by adding console.log(req.url);
To avoid this:
var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
if(req.url === '/'){ // or if(req.url != '/faicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
// res.writeHead(200);
}).listen(2000);
A request is made to favicon.io automatically.
To avoid automatic request to favicon, you can do the following
http.createServer(function(req, res){
if(req.url != '/favicon.ico'){
fs.readFile('sample.txt', function(err , sampleData){
console.log(String(sampleData));
res.end();
});
console.log("The end");
}
}).listen(2000);
O/p =>
The end.
this is sample text for the testing.
You may pipe the file to the client:
fs.createReadStream('sample.txt').pipe(res);
As I am a newbie to Node.js and is learning from different articles. So, far I have learnt, my code is
At server side with app.js
var http = require('http');
var app = http.createServer(function(req,res)
{
req.on('end',function()
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello');
});
});
var io = require('socket.io').listen(app);
io.sockets.on('connection',function(socket)
{
socket.emit('connect',{msg:'Hello Client'});
socket.on('client_Says',console.log);
});
app.listen(3000);
At client side with index.html
<script type="text/javascript" src="//localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('//localhost:3000');
socket.on('connect',function(data)
{
alert('Server says '+data.msg);
socket.emit('client_Says',{data:'Hello Server'});
});
</script>
What is that I am doing wrong in above code? When I run app.js in console, it says info - socket.io started but when I run http://localhost:3000 it just keep requesting server.
plus I want to know that is it true that wherever on my pc I create my folder for Node and place app.js and index.html files like above in it and run http://localhost:3000 in browser will automatically make that folder my site folder for localhost after running app.js in Node console?
In your app.js update code to this
var http = require('http'),
fs = require('fs'), //<--- File Module
index = fs.readFileSync(__dirname + '/index.html');
var app = http.createServer(function(req,res)
{
res.writeHead(200, {'Content-Type': 'text/html'}); //<-Updated to text/html
res.end(index); //<---I am sending page
});
Hope that solves your problem
You're not supposed to do this on server side:
socket.emit('connect',{msg:'Hello Client'});
because connect is a default event which is emitted on a successful connection from the server. So when a client connects, the server fires its default 'connect' event, but here you're also triggering your event named connect which might be causing problem.
I am new to Node.js, so I figured I would check it out and do a hello world. I have been having the same issue on all three of my machines, a Win 8, Win 7 and a Mac. Thought at first it was a firewall issue, but I checked and it was off on both Mac and Windows 8 machines (didn't bother checking the win7). When I run Node from the terminal the browser waits for localhost, then eventually times out. I have been at this for two days, can't seem to find any solution via Google. What am I missing.?
Here is my code:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
You don't need to wait for the HTTP request to end (besides that request.on('end', ..) isn't valid and never fires, and that's why you time out). Just send the response:
var http = require("http");
console.log("file loaded");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello HTTP!');
}).listen(8080);
Although if you want an easier way to create a HTTP server, the simplest way would be to use frameworks such as Express. Then your code would look like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.set('Content-Type', 'text/plain');
res.send(200, 'Hello HTTP!');
});
app.listen(8080);
You can also use the connect middleware. Just install it first using npm like so:
npm install -g connect
After this you can make a very simple app like this:
var app = connect()
.use(connect.logger('dev'))
.use(connect.static('public'))
.use(function(req, res){
res.end('hello world\n');
})
.listen(3000);
You can get more information regarding connect here. I tell you to use this, because you get a very simple server, that is easily extensible. However, if you want to make pull blown web sites, then I would sugges using expressjs.