2

I'm new kid on the block with NodeJS. Right now im following a basic tutorial of NodeJS, so far so good.

But I have a problem using fs.createReadStream method:.

var http = require("http");
var fs = require("fs");

function fourOHfour(response) {
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("four oh four.....");
    response.end();
}

function onRequest (request, response) {
    if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200, {"Content-Type": "text/plain"});
        fs.createReadStream("./index.html").pipe(response);
    }
    else{
        fourOHfour(response);
    }
}

http.createServer(onRequest).listen(8888);
console.log("server is running......");

When I go on my browser and type localhost:8888, it should be rendering the index.html file in HTML but the result is wrong, all I get is a bunch of codes of index.html file - plain text.

error localhost:8888

Meanwhile in my sublime compiler, I've got no error in regards to this case. Until i try to edit my code, whatever I cahnge, it will give me an error like this:

error sublime compiler

If that thing happen, I cant fix the error unless I restart the laptop, then everything running well again. At least my compiler say that the server is running... Even thought my localhost:8888 still not rendering the HTML file.

1
  • how You launch Your code? why to restart? maybe some other process using 8888 try to use 8080 or something else. or kill nodejs processes, by doing: killall node Commented Mar 24, 2016 at 12:50

2 Answers 2

1

You are specifying your content type as: text/plain which means the page will not render in HTML but instead, plain text. This is why you see the "codes" from your HTML file instead of the actual HTML being rendered.

To fix that problem, set the content type to text/html like so:

response.writeHeader(200, {"Content-Type": "text/html"});

In regards to the error you posted, "EADDRINUSE"

EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.

So, in your case, there must be running a server on port 8888 already. Check for the listening event like this, to see if the server is really listening:

var http=require('http');

var server=http.createServer(function(req,res){
    res.end('test');
});

server.on('listening',function(){
    console.log('ok, server is running');
});

server.listen(8888);
Sign up to request clarification or add additional context in comments.

Comments

0

EADDRINUSE - seems like port is busy by another process or maybe by same nodejs process that don't want to close.

try to kill process:

killall node

about code - try this:

var http = require("http"),
    fs = require("fs"),
    URL = require('url');

function output(response, body, status) {
    status = status || 200;
    response.writeHead(status, {"Content-Type": "text/html"}); 
    response.end(body);
} 

function fourOHfour(response) {
    output(response, 404, "four oh four...");
}

function onRequest (request, response) {
    var uri = URL.parse(request.url).pathname; // extractin URI part
    var method = request.method || 'GET'; // detecting method otherwise GET

    if(method == 'GET' && uri == '/'){
        // reading file
        fs.readFile(__dirname+'/index.html', function(err, data) {
          if(err) { // if error happen, output error
            output(response, err, 500);
            return;
          }

          output(response, data); // ouput html body
        });
        return;
    }

    fourOHfour(response);
}

var httpServer = http.createServer();
    httpServer.on('request', onRequest);
    httpServer.listen(8888);

To run Your code in production do following in terminal:

  1. install forever:

    sudo npm install -g forever # remove sudo word if You use windows, or You're already root user

  2. start app using forever:

    forever start app.js

To run Your code in development environment:

  1. install nodemon:

    sudo npm install -g nodemon # remove sudo word if You use windows, or You're already root user

  2. run Your app using nodemon:

    nodemon app.js

Forever will keep Your app running and will output logs which You can see using:

forever list    # lists running processes
forever logs    # shows logs that outputs forever
forever logs 0  # read logs of 0-th process

To restart forever process:

forever restartall  # restarts all forever instances 
forever restart 0   # restarts first process 

To stop:

forever stopall
forever stop 0

About Nodemon: it's a tool that watches changes in Your file and restarts it automatically, no need to stop-start Your app, so that's why I prefer nodemon in dev environment

8 Comments

in order to kill the processm where to put this "killall node" code ? im using sublime text 3 as my editor and compiler
no where just call it in terminal before running process
am i missing something? i do compile my node using sublime build system, so im not using any terminal. i did write killall node in my sublime compiler, but still if port 8888 busy, i cant kill/stop nodejs instances
sublime is not compiler. it's just editor. You use terminal to run Your app, in case of sublime maybe it has terminal plugin.
oh since i cant use your solution, i found new one. im using windows btw. go to cmd. type tasklist. and then type taskkill / F / PID [pid-number-of-node.exe]. thankyou very much for your help mate.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.