node.js学习笔记(一)

node.js简介

node.js是单线程、异步、事件驱动的。
特点:速度快但是耗内存多。
开始第一段代码:

1
2
3
4
5
6
7
8
9
var http = require("http");
http.createServer(function (request,response){
response.writeHead(200,{'Content-Type':'Text/html',charset=utf-8});
if(request.url!=="/favicon.ico"){ //清除第二次访问
console.log("在服务器端打印的内容");
response.write("服务器返回给前端的内容");
response.end(""); //如果没有这行,http协议结束不了!
}
}).listen(8000);

函数调用

函数调用有两种方式,一种是本地函数调用,另一种是调用其它文件中的函数。

其他文件中的函数调用

1
var otherFileFun = require("./module/other.js");

这行代码是在本地文件中使用的,其目的类似对函数进行声明。这样我们就可以在本地文件中使用其他文件(other.js)中给我们开放接口的函数了。那么在other.js中如何开放接口呢?

1
2
3
4
5
//other.js文件中的内容:
function other(){
console.log("other File");
}
module.exports = other;

这是第一种开放接口的方法,但这样在一个js文件中只能开放一个函数的接口。还有另一种方式开放接口:

1
2
3
4
5
6
7
8
9
10
11
//重新写other.js的内容
module.exports {
func1:function(){
console.log("function 1");
return "function 1";
},
func2:function(){
console.log("function 2");
return "function 2";
}
}

使用这种类似返回一个对象字面量的方式开放接口,就可以在一个js文件中同时开放几个函数的接口了。在本地文件中调用的时候,使用调用对象方法的形式就可以调用了。

1
2
var other1 = otherFileFun.func1();
var other2 = otherFileFun["func2"]();

一个在减肥的蓝胖纸<br><br>阳光正能量小王子<br>…^_^…