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..."); }