
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")
}
}运行结果:

以上就是node函数怎么被调用?的详细内容,更多请关注易知道|edz.cc其它相关文章!














