Testing Node.JS server


#1

So I am very to node.js. I have netbeans and also a few front-end environments like atom.

The first exercises consist of code that creates a server, and then other code that sends a request to that server. I am just confused about how to test both ends of the code in this situation. Should I just enter all the code (see below) into one js document in netbeans and run it? (already have tried this… and didn’t see any useful output but also no errors) or do I have to put the request code in a browser side environment like atom and the server in a node.js/netbeans project?

var http = require("http");
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-type": "text/plain"});
    request.on("data", function(chunk) {
        response.write(chunk.toString().toUpperCase());
    });
    request.on("end", function() {
        response.end();
    });
    }).listen(8000);
var http = require("http");
var request = http.request({
    hostname: "localhost",
    port: 8000,
    method: "POST"
}, function(response) {
    response.on("data", function(chunk) {
        process.stdout.write(chunk.toString());
    });
});
request.end("Hello World");

#2

You can certainly do this if you’re just playing around.

I’m not sure what output you expect… you’re ending the request with “Hello World”, the server receives that request chunk, transforms it to upper-case, and writes it to the response, which again the request receives and writes to stdout; so what you’ll see is “HELLO WORLD”.

Not sure what netbeans does though, maybe try running it from a regular shell.


#3

I did not see the “HELLO WORLD” output as it should… I will try again.


#4

So when I try to run it all as one file in netbeans, it is first displaying nothing, then when I run it again it is saying: “throw er; // Unhandled ‘error’ event Error: listen EADDRINUSE :::8000”

I tried a few different random ports and it didn’t change anything…


#5

This has been resolved!


#6

That means port 8000 is in use by something else.

I would strongly advise to not run this through Netbeans and to run it in your console. Netbeans is not the way most people run Node.js in development. Your problem is probably coming from something weird Netbeans is doing.