【原创】nodejs探索笔记 -- 002
上次说到环境的搭建,但是忘记说目录结构了。
作为一个整体的学习,探索,研究的一个项目当然是要把所有的资源,代码,配置文件等用到的所有这个生态系统所需要用到的放在同一个文件夹下,这个文件夹我将其命名为A。当然,其中根据不同的文件的不同用途划分模块文件夹。例如共通的模块放在ACommon中,服务器的模块放在AServer中等等。大概目录结构如下:
/A
/A/ACommon
/A/AServer
/A/AServer/js
/A/AServer/js/AServer.js
/A/AServer/index.html
/A/AServer/package.json
/A/AServer/AServer.png
/A/core
/A/core/node.exe
/A/node-webkit
/A/node-webkit/credits.html
/A/node-webkit/ffmpegsumo.dll
/A/node-webkit/icudt.dll
/A/node-webkit/libEGL.dll
/A/node-webkit/libGLESv2.dll
/A/node-webkit/nw.exe
/A/node-webkit/nw.pak
/A/node-webkit/nwsnapshot.exe
/A/startAServer.bat
其中新建了一个文件/A/AServer/js/AServer.js用于接下来要学习和练习的代码了。
首先参考《Node入门》中第一段代码,也就是创建一个最简单最基础的HTTP服务器。将一下代码保存到AServer.js文件中。
1 var http = require("http"); 2 3 http.createServer(function(request, response){ 4 response.writeHead(200, {"Content-Type": "text/plain"}); 5 response.write("Hello Word!"); 6 response.end(); 7 }).listen(8888);
然后刷新页面。然后在浏览器中输入http://localhost:8888/就可以看到网页打开后显示了Hello Word!
但是这点成就并不能让我满足。不只是浏览器,还要在客户端也能访问到服务才好。于是在文件夹A下新建了一个AClient文件夹。其中的文件构成和AServer基本一致,只不过其中几乎所有的AServer的地方全部换成了AClient。代码如下:
/A/AClient/package.json
1 { 2 "name": "AClient", 3 "main": "index.html", 4 "description": "A Client", 5 "version": "0.1.0", 6 "keywords": ["AClient", "node", "nodejs", "node.js", "node-webkit"], 7 "window": { 8 "title": "AClient", 9 "icon": "AClient.png", 10 "toolbar": true, 11 "frame": true, 12 "width": 800, 13 "height": 500, 14 "position": "mouse", 15 "min_width": 400, 16 "min_height": 200, 17 "max_width": 800, 18 "max_height": 600 19 }, 20 "webkit": { 21 "plugin": true 22 } 23 }
/A/AClient/index.html
1 <html> 2 <head> 3 <title> 4 Hello World! 5 </title> 6 <script src="js/AClient.js"></script> 7 </head> 8 <body> 9 <h1> 10 AClient 11 </h1> 12 </body> 13 </html>
/A/AClient/AClient.png也将颜色稍作改变,以与AServer区分。
/A/AClient/js/AClient.js
1 window.onload = function(){ 2 window.location.href = "http://localhost:8888"; 3 }
/A/startAClient.bat
1 #start AClient 2 "%cd%\node-webkit\nw.exe" "%cd%\AClient"
OK!无论是B/S模式还是C/S都畅通无阻了,接下来参考《Node入门》优化一下服务器代码,将其变成一个服务模块,并将模块分离到文件/A/AServer/js/AHTTPServer.js。
AHTTPServer.js
1 var http = require("http"); 2 3 exports.startAHTTPServer = function() { 4 http.createServer(function(request, response){ 5 console.log("Request received."); 6 7 response.writeHead(200, {"Content-Type": "text/plain"}); 8 response.write("Hello Word!"); 9 response.end(); 10 }).listen(8888); 11 12 console.log("Server has started."); 13 }
/A/AServer/js/AServer.js代码如下。
1 var aHTTPServer = require("./js/AHTTPServer"); 2 3 aHTTPServer.startAHTTPServer();
这里有一点需要注意。就是引用自己写的模块的时候,相对路径都是从项目的根目录开始的。这个项目的根目录就是文件夹A。
OK!服务器模块拆分完毕,下一步要整更高深的东西了——路由。