Document directory
- I. Introduction
- Ii. Installation instructions
- 3. Simple Hello World Program
- 4. route different requests
- 5. Advanced Development (loading static html/JS/CSS files)
- 6. Introduction to the python lightweight Web framework bottle
I. Introduction
Nodejs is a lightweight webserver framework. Similar to Python's bottle, nodejs is a lightweight Web framework. To write a Web server, you only need one line of code.
The node. js platform is built based on Chrome's JavaScript runtime, which encapsulates the googlev8 engine (applied to Google Chrome. The V8 engine executes Javascript very quickly and performs very well. Node optimizes some special use cases and provides an alternative API to make V8 run better in a non-browser environment.
Node. js Official Website: http://www.nodejs.org/
Bottle Official Website: http://bottlepy.org/docs/dev/
Ii. Installation instructions
The installation commands in Linux are as follows:
Wget http://nodejs.org/dist/v0.10.5/node-v0.10.5.tar.gz
Tar zxvf node-v0.10.5.tar.gz
CD node-v0.10.5.tar.gz
./Configure -- prefix =/home/zhaolincheung/local/nodejs
Make & make intall
Note: Install node. js in the/home/zhaolincheung/local/nodejs directory. Node. JS installation requires Python or later. Otherwise, it will be executed. /configure error; node. JS also needs the support of GCC-C ++, so the system needs to install gcc-C ++.
Use node-V to check whether the installation is successful. If "v.0.10.5" is returned, the installation is successful.
Node. js has been compiled and installed. To uninstall the SDK, run make Uninstall.
3. Simple Hello World Program
To learn any language or framework, you must first write the hello World Program. This is also the case here. Let's write a simple hello World Program.
First, write helloworld. js with the following content:
var http = require('http');http.createServer(function(req, res) { res.writeHead(200, {'Content-Type':'text/plain'}); res.end('Hello World\n');}).listen(10001);console.log('Server running at http://127.0.0.1:10001/');
Second, execute the file:/home/zhaolincheung/local/nodejs/bin/node helloworld. js
Finally, you can access http: // 127.0.0.1: 1337 through a browser and get a hello World response.
4. route different requests
When we are using node. when JS is developed. JS is single-threaded, so for time-consuming operations, we encapsulate it into a function and call it using a callback function, so that the code can continue to be executed. When the time-consuming operation is placed in the callback function, after the time-consuming operation is completed, the callback function will continue to execute the remaining code in the function, and it will not delay other methods (requests) outside the callback function). This is the legendary callback. We pass a function to a method, which calls this function for callback when a corresponding event occurs. This is the event-driven Asynchronous Server-side JavaScript and its callback!
The author on the Internet saw a good node. js entry information, share with you, reference link: http://www.nodebeginner.org/index-zh-cn.html
The following example describes how to process (route) different requests (URLs ). It contains four files: Index. JS, server. JS, router. JS, and requesthandlers. js.
Specifically, index. js defines the corresponding processing (Routing) methods for different requests (URLs), and starts webserver.
The index. js code is as follows:
var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); var handle = {}; handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/upload"] = requestHandlers.upload; server.start(router.route, handle);
Server. JS is the implementation of server creation and startup. The server. js code is as follows:
var http = require("http"); var url = require("url"); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); route(handle, pathname, response); } http.createServer(onRequest).listen(65535); console.log('Server has started.'); } exports.start = start;
The onrequest function above is the callback function.
The callback function calls a function F1 as a parameter of function F2, so that F2 will not affect the execution of the following code because of the time-consuming operation of F1. F1 will wait for the triggering of the corresponding event, that is, F1 and F2 are executed in parallel.
Router. js processes different URL calling functions (namely, the following handler [pathname] (response. The Code of router. JS is as follows:
function route(handle, pathname, response) { console.log("About to route a request for "+ pathname); if (typeof handle[pathname] == 'function') { handle[pathname](response); } else { console.log("No request handler found for " + pathname); response.writeHead(404,{'Content-Type': 'text/plain'}); response.write('node.js: 404 Not found'); response.end(); } } exports.route = route;
Requesthandlers. JS is the specific implementation of different URL call (Routing) methods. The requesthandlers. js code is as follows:
function start(response) { console.log("Request handler 'start' was called."); response.writeHead(200, {'Content-Type': 'text/plain'}); response.write("node.js: hello,start"); response.end(); } function upload(response){ console.log("Request handler 'upload' was called."); response.writeHead(200, {'Content-Type': 'text/plain'}); response.write("node.js: hello,upload"); response.end(); } exports.start = start; exports.upload = upload;
The command for running this example is: node index. js
When the request is http: // 127.0.0.1: 65535/, the running result is as follows:
The running result after the request: http: // 127.0.0.1: 65535/upload is as follows:
Code link: https://github.com/zhaolincheung/nodejs_demo
5. Advanced Development (loading static html/JS/CSS files)
The following is based on the above example: it can meet the needs of the. html page, the. js file, and the. CSS file. Modify server. js as follows:
VaR HTTP = require ("HTTP"); var url = require ("url"); var FS = require ('fs'); var Path = require ('path '); vaR root = '/home/zhaolianxiang1/test_nodejs'; // define the file's root directory function start (route, handle) {function onrequest (request, response) {var pathname = URL. parse (request. URL ). pathname; console. log ("request for" + pathname + "received. "); // get the file suffix var ext = path. extname (pathname); Switch (EXT) {Case '.html ': Case '.css': Case '. js': var realpath = root + pathname; // determines whether the requested file has a path. exists (realpath, function (exists) {If (exists) {// read the file FS. readfile ('. '+ request. URL, 'utf-8', function (ERR, data) {If (ERR) Throw err; response. writehead (200, {"Content-Type ":{". html ":" text/html ",". CSS ":" text/CSS ",". JS ":" application/JavaScript ",} [ext]}); response. write (data); response. end () ;}) ;}else {// the requested file does not exist response. writehead (404, {"Content-Type": "text/html"}); response. end ("
Then, create another file index.html under the current directory.
Okay. Let's take a look at the running result. Enter http: // 127.0.0.1: 65535/index.html in the browser. The running result is as follows:
Enter http: // 127.0.0.1: 65535/start in the browser. The running result is as follows:
Reference: http://www.cnblogs.com/rubylouvre/archive/2011/11/20/2255083.html
6. Introduction to the python lightweight Web framework bottle
Compile a file bottle_example.py with the following content:
from bottle import route, run, template, static_file@route('/hello')def hello(): return "Hello,world!"test_home = './resource/'@route('/rsrc/<p:path>')def foo(p): return static_file(p, test_home)run(host='localhost', port=8080)
Run the file and enter http: // localhost: 8080/hello in the browser. The page will output "Hello, world ".
As follows:
Okay, the webserver is running. Exist in the./resource/docs/directory ). Shows the directory structure:
Because bottleis Based on Response Processing, how can we allow bottleto access this index.html page?
The answer is:@ Route ('/rsrc/<P: path> ')This route can be implemented. When the user opensHttp: // localhost: 8080/rsrc/docs/index.htmlThis route will be triggered and then executedStatic_fileThis method is used to load the static file specified by the path. This allows you to load static pages.