Nodejs-simple http server example

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.