Nodejs的基本語法
Nodejs Js的編譯運行環(huán)境,運行在服務(wù)器端的 JavaScript,事件驅(qū)動I/O服務(wù)端JS運行環(huán)境,
基于Google的V8引擎,執(zhí)行JS的速度非???,性能非常好。
Js基礎(chǔ)知識學(xué)習(xí)參考 W3cSchool
- Vim創(chuàng)建test.js的nodejs文件
var name = "Hello World!"; console.log(name);
服務(wù)器端執(zhí)行 node test.js , 屏幕上打印出 Hello World!,
- if 流程控制
if ( ) { }
else if ( ) { }
else { }
- for 循環(huán)語句
for (var i; i < 10; i++) { }
- switch case 語句
switch ( n )
{
case 1:
執(zhí)行代碼 1
break;
case 2:
....
default:
}
創(chuàng)建http服務(wù)器
- 引入Nodejs的核心模塊http
const http = require("http"); //引入http模塊
const ip = ""; //設(shè)置服務(wù)器IP地址
const port = ; //設(shè)置服務(wù)器端口
- 通過res, rep 參數(shù)來接收和響應(yīng)數(shù)據(jù)
var a =function(req, res) {
res.writeHead(200, {'content':'text/html'} ); //發(fā)送http頭部,http狀態(tài)值200,內(nèi)容類型text/html
res.end("Hello World \n"); //發(fā)送相應(yīng)數(shù)據(jù)Hello World
}
- createServer創(chuàng)建http服務(wù)器
var server = http.createServer( a );
- 終端打印信息
var c = function(){
console.log("Server is running at http://", http);
}
- 監(jiān)聽端口
server.listen( port, ip, c);