Node. js development manual (2)

Source: Internet
Author: User
Tags node server
Document directory
  • 1. index.html
  • 2. Script. js
  • 3. styles.css
  • 4. Write the node Program
Node. js development manual (2)

Author: chszs, reprinted with note. Blog homepage: http://blog.csdn.net/chszs
I. static file service

If we want to use files on the disk as Web content to provide external services, how can we use node? The answer is to use the FS module.
We can use FS, the filesystem module, to load the file content and pass the content through the createserver callback function. Providing static file services is the core basic function of node. js and should be mastered.

Ii. Demo

Next we will create three files which will be provided by nodejs for static file service.
1. index.html

The content is as follows:

2. Script. js

The content is as follows:

// script.jswindow.onload=function(){    alert('Yay Node!');};

3. styles.css

The content is as follows:

#yay{    font-size: 5em;    background: blue;    color: yellow;    padding: 0.5em;}

Put the preceding three files in the content directory.

4. Write the node Program

Create a script file named server. js with the following content:

var http = require('http');var path = require('path');var fs = require('fs');http.createServer(function(req, res){    var lookup = path.basename(decodeURI(req.url)) || 'index.html',    f = 'content/' + lookup;    fs.exists(f, function(exists){        console.log(exists ? lookup + " is there" : lookup + " doesn't exist");    });}).listen(8080);

Run the above program with the supervisor hot deployment tool:
$ Supervisor server. js

Access address in the browser: http: // localhost: 8080/foo
Terminal display:
Debug: Starting child process with 'node server. js'
Foo doesn' t exist

Access URL in the browser: http: // localhost: 8080/index.html
Terminal display:
Debug: Starting child process with 'node server. js'
Debug: Watching directory '/home/chszs/tmp' for changes.
Index.html is there

Iii. Advanced

If we want the client to know the file type, we can use the extension to determine.
Modify the server. js file with the following content:

// server.jsvar http = require('http');var path = require('path');var fs = require('fs');var mimeTypes = {    '.js': 'text/javascript',    '.html': 'text/html',    '.css': 'text/css'};http.createServer(function(req, res){    var lookup = path.basename(decodeURI(req.url)) || 'index.html',    f = 'content/' + lookup;    fs.exists(f, function(exists){        if(exists){            fs.readFile(f, function(err, data){                if(err){                    res.writeHead(500);                    res.end('Server Error!');                    return;                }                var headers = {'Content-type': mimeTypes[path.extname]};                res.writeHead(200, headers);                res.end(data);            });            return;        }        res.writeHead(404);        res.end();    });}).listen(8080);

In the browser address bar, enter
Http: // localhost: 8080/styles.css
Or
Http: // localhost: 8080/script. js
The file content is displayed on the webpage.

In the browser address bar, enter
Http: // localhost: 8080/index.html
:

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.