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
: