Build a simple http server with the following code: [javascript] // server. jsvarhttprequire (& amp; #39; http & amp; #39;); varserverhttp. createServer (function (request, response) {require (& amp; #39 ;. & amp ;#
Build a simple http server with the following code:
[Javascript]
// Server. js
Var http = require ('http ');
Var server = http. createServer (function (request, response ){
Require ('.' + request. url );
Response. end (global. output );
});
Server. listen (8080 );
The function is simple. First, create an HTTP Server and listen to port 8080.
Run the server:
[Plain]
# Node server. js
Or
# Node server. js &
Add & to indicate execution in the background.
Run the following command to check whether port 8080 is listened:
[Plain]
# Netstat-tln
The callback method directly contains the script specified by request. url, and then outputs the content in the global. output variable.
The following is a test script:
[Javascript]
// Hello. js
Global. output = "Hello World! \ N ";
Save as hello. js, put it in the same directory of server. js, and then test it with the following command:
[Plain]
# Curl http: // 127.0.0.1: 8080/hello. js
We should see "Hello World! "Output.
The hello. js file is the script file name.
Add error handling (not included in the sample code for ease of viewing), even if it is a real http server.