I
I
ink2018-03-08 05:55:39
Node.js
ink, 2018-03-08 05:55:39

Error running server.js, how to fix?

Why did I get an error when starting the server?

server.js

var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
port = process.argv[2] || 65535;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 65535));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");

Always swears on a bad port:
error port

RangeError [ERR_SOCKET_BAD_PORT]: Port should be > 0 and < 65536. Received NaN.
at Server.listen (net.js:1499:13)
at Object. (C:\Users\Lensky\Desktop\server\server.js:35:4)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:194:16)
at bootstrap_node.js:618:3

how to fix ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-08
@AskMy

listen(parseInt(port, 65535))

Which is not surprising. For any radix greater than 36, the result of parseInt is NaN, according to the specification.
An obvious typo, it is obvious that 65535 is supposed to be the default value, and not the base of the number system.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question