简单的说 Node.js 就是运行在服务端的 JavaScript。Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。下面我们来看一下node中怎么函数怎么调用。
1.js文件内部函数调用var http = require('http')
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
if(request.url="/favicon.ico"){
fun1(response);
response.end('')
}
}).listen(8888);
function fun1(res) {
console.log("我是fun1")
res.write("你好,我是fun1|")
}
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
运行结果:
2.调用其他js文件内的函数
m1.js文件内容var http = require('http')
var fun2 = require("./m2.js")
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
if(request.url="/favicon.ico"){
fun1(response);
fun2(response);
response.end('')
}
}).listen(8888);
function fun1(res) {
console.log("我是fun1")
res.write("你好,我是fun1|")
}
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
ps:m2.js与m1.js在同一目录下这里用的是相对路径调取
m2.js文件内容function fun2(res) {
console.log("我是fun2")
res.write("你好,我是fun2")
}
module.exports = fun2;//只能引用一个函数
运行结果:
在这个例子中我们成功调用了m2.js文件中fun2函数,我们使用的是module.experts = 的方法,这个方法有一 个弊端:只能调用一个函数,如果我们想调用多个函数如下
3.调用其他js文件中多个函数
我们m1.js文件修改为var http = require('http')
var funx = require("./m2.js")
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
if(request.url="/favicon.ico"){
fun1(response);
funx.fun2(response);
funx.fun3(response);
response.end('')
}
}).listen(8888);
function fun1(res) {
console.log("我是fun1")
res.write("你好,我是fun1|")
}
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
我们将m2.js文件修改为module.exports ={
fun2:function (res) {
console.log("我是fun2")
res.write("你好,我是fun2|")
},
fun3:function (res) {
console.log("我是fun3")
res.write("你好,我是fun3")
}
}
运行结果: