1

i have a simple node script

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337);

now when i run this, i can go to localhost:1337 and see the output but , in the command module, its frozen for some reason. until i press ctrl+C its frozen and only after Ctrl+C im allowed to execute more files.

is this just me or its the way it was designed. If it is can someone point me in the right direction as to how to have it always listen on port 1337 or another for different files.

8
  • which version of node are you running? I copy pasted yours into mine (0.10.9) and was fine (could get an http response on 1337, but could still type into the prompt) Commented Aug 1, 2013 at 19:43
  • im running 0.10.15 .... mine gets stuck until ctrl+c Commented Aug 1, 2013 at 19:48
  • from their website its nodejs.org/download 0.10.15 which is the current version , on and btw its on windows 8 with node js command prompt. Commented Aug 1, 2013 at 19:55
  • Why not just run another terminal? Commented Aug 1, 2013 at 20:06
  • 3
    @user1690718, It's not getting stuck, it's waiting for more connections. You created an HTTP server which is listening for connections. Until you stop that server, your code won't exit. Commented Aug 1, 2013 at 20:08

1 Answer 1

2

This is normal behavior. Node will only exit if there's nothing more to do (or if you manually stop it via Ctrl+C). Since you told http to listen(), the process will stay alive indefinitely.

It's not exactly clear what you're asking, but if you want to run additional files inside your app, you simply require() them.

var otherFile = require('./otherFile.js') // the .js is optional

otherFile will now be set to whatever you do to module.exports in otherFile.js.

You should read the module documentation to get a full understanding of how require works.

If you want to run other unrelated files with node at the same time, open a separate command prompt window.


I will now read between the lines a little: it looks like you might be wondering how to get http to serve files from disk like other web servers. Node doesn't work like traditional web servers. Your code has to explicitly handle serving up things from disk.

Fortunately, there are frameworks/libraries that make it easy to do. If you're building any kind of web service, you should really use a framework rather than the raw http module. I recommend looking at Express. It's easy to serve files from disk with express.static.

Sign up to request clarification or add additional context in comments.

Comments

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.