hi
i have just started learning nodejs. i wrote this simple code

var http = require("http");
var fs=require('fs');
var wbsocket = ('ws');

http.createServer(function(req, res) {

    res.write('2working');

}).listen(8889);

console.log('listing to port 8080');

and run in cmd node filename.js
in cmd doesnt give me any error and when i open webbrowser its continue loading and after 1mint says webpage not avilable.
so please tell me what i have wrong done ?

Hi, in order to write a response you have to send an header and then call end():

res.writeHead(200, {'Content-Type': 'text/html'});
res.write('2working');
res.end();

Also, probably mistype, on console log you wrote that it listens on port 8080, but it's executing on 8889.

Docs:

i tried also with res.send("hello world"); but wasnt working

Ok, does it work now?

Applying the end() method after you write the response body is mandatory. About the headers: if not defined, Node will set implicit headers, but you should always set a status [code|message] response:

By the way, you last attempt wasn't working for you because the send() method does not exists in the http module.

o yes it isnt node function... it was express module function..

is it neccessary to add

res.writeHead(200, {'Content-Type': 'text/html'});

?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.