第一个nodejs程序,helloworld解析
前提:本机已安装nodejs包 (若果不了解,请参考本文最下端附注链接)
1. 文档建立
新建js文档名http.js
编写内容:
var http = require('http');//创建http对象 //建立一个请求监听方法 function requestListenter(request,response){ response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('Hello nodejs\n'); } //创建http服务器 http.createServer(requestListenter); //开启http监听服务,为防止与其他端口冲突,这里使用了:8888,当然也可以写成别的 http.listen(8888); console.log('IPAddress http://127.0.0.1:8888/ or http://localhost:80');
2.从cmd下进入此文档的物理路径下
使用 node http.js 命令执行,可以看到以下提示:
IPAddress http://127.0.0.1:8888/ or http://localhost:8888
这时在浏览器中输入以上地址就可以访问您刚刚新建的的网站了。
3.代码优化
很多时候你看到别人代码是这么写的,甚至jquery中代码看不懂,接下来,简要解释一下
var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, { "Content-Type": "text/html" }); response.write("Hello World!"); response.end(); }).listen(8888); console.log('IPAddress http://127.0.0.1:8888/ or http://localhost:80');
1.匿名方法:
http.createServer(function(request, response) {}) 这里省略了requestListener定义直接使用匿名方法
2. 链式编程
目前大多数语言均支持链式编程
http.createServer(function(request, response) {}).listent(8888); 如果前面方法返回的对象,还有其他属性、方法操作,就可以继续链式下去
4.对于js的函数、匿名函数、面向对象,不太理解的请查询资料
这里有个简述概要:javascript基础概要复习(类型、数组、函数、面向对象)
更多请查阅:w3school
浙公网安备 33010602011771号