var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type":"text/plain"}); response.write("Hello node.js"); response.end(); }).listen(8888);
node.js有个特殊的require,用于同步加载其余模块的对象,这与其余语言的require, import差很少。能同步就是好,不像前端那样一层套一层。而后利用一个函数去实例化一个服务器对象,而后监听8888端口。这是node.js官网最初的例子,你们都写烂了。但这样的程序在现实中一无可取,咱们在地址栏上输入URL,你起码要返回一个完整页面给我吧!
var http = require("http"); exports.start = function(){ http.createServer(function(request, response) { console.log("Request received..."); response.writeHead(200, {"Content-Type":"text/plain"}); response.write("Hello node.js"); response.end(); }).listen(8888); console.log("server start..."); }
而后咱们再建一个index.js做为入口(index.js与server.js放在同一目录下)。
var server = require("./server"); server.start();
<!doctype html> <html> <head> <title>index</title> <metacontent="IE=8"http-equiv="X-UA-Compatible"/> <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"> </head> <body> <h2>这是首页</h2> </body> </html>
如今咱们就在要请求过来时,把此页的内容读出来,返给用户。这时咱们就要用到fs模块的方法了。
var http = require("http"); var fs = require('fs'); exports.start = function(){ http.createServer(function(request, response) { fs.readFile('./index.html','utf-8',function(err, data) {//读取内容 if(err) throw err; response.writeHead(200, {"Content-Type":"text/html"});//注意这里 response.write(data); response.end(); }); }).listen(8888); console.log("server start..."); }
window.onload = function(){ varp = document.createElement("p"); p.innerHTML ="这是动态添加的" document.body.appendChild(p); }
再建一个styles目录,里面建index.css,内容以下:
html,body{ background:#3671A5; height: 100% }
而后在index.html引入这两个文件:
<!doctype html> <html> <head> <title>index</title> <metacontent="IE=8"http-equiv="X-UA-Compatible"/> <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"> <linktype="text/css"rel="stylesheet"href="styles/index.css"/> <scriptsrc="/javascripts/index.js"></script> </head> <body> <h2>这是首页</h2> </body> </html>
var http = require("http"); var fs = require('fs'); var url = require('url'); exports.start = function(){ http.createServer(function(request, response) { varpathname = url.parse(request.url).pathname; varext = pathname.match(/(\.[^.]+|)$/)[0];//取得后缀名 switch(ext){ case".css": case".js": fs.readFile("."+request.url,'utf-8',function(err, data) {//读取内容 if(err) throw err; response.writeHead(200, { "Content-Type": { ".css":"text/css", ".js":"application/javascript", }[ext] }); response.write(data); response.end(); }); break; default: fs.readFile('./index.html','utf-8',function(err, data) {//读取内容 if(err) throw err; response.writeHead(200, { "Content-Type":"text/html" }); response.write(data); response.end(); }); } }).listen(8888); console.log("server start..."); }