node web demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| var http = require('http'); var fs = require('fs'); var url = require('url'); http.createServer( function (request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); fs.readFile(pathname.substr(1), function (err, data) { if (err) { console.log(err); response.writeHead(404, {'Content-Type': 'text/html'}); }else{ response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data.toString()); } response.end(); }); }).listen(8081); console.log('Server running at http://127.0.0.1:8081/');
|
使用 Node 创建 Web 客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var http = require('http'); var options = { host: 'localhost', port: '8081', path: '/index.htm' }; var callback = function(response){ var body = ''; response.on('data', function(data) { body += data; }); response.on('end', function() { console.log(body); }); } var req = http.request(options, callback); req.end();
|