本地函数
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (request.url !== "/favicon.ico") { //清除第2此访问
fun1(response)
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//---普通函数
function fun1(res) {
console.log("fun1")
res.write("你好,我是fun1");
}
浏览器:

控制台:

调用另外一个js文件的函数
1.同级目录下新建文件夹modules,进入文件夹新建一个文件
│ 02_funcall.js
└─ modules
└─otherfuns.js
2.otherfuns.js
function fun2(res) {
console.log("fun2")
res.write("hello, 我是fun2")
}
// 如果要声明为可被外部调用的
module.exports = fun2
3.修改原来的02_funcall.js
var http = require('http');
var otherfun = require("./modules/otherfuns.js")
http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (request.url !== "/favicon.ico") { //清除第2此访问
fun1(response)
otherfun(response)
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//---普通函数
function fun1(res) {
console.log("fun1")
res.write("你好,我是fun1");
}
浏览器:

控制台:

导出多个函数
otherfuns.js
//支持多个函数
module.exports = {
getVisit: function() {
return visitnum++;
},
add: function(a, b) {
return a + b;
},
fun2: function(res) {
console.log("fun2")
res.write("hello, 我是fun2")
},
fun3: function(res) {
console.log("fun3")
res.write("hello, 我是fun3")
}
}
02_funcall.js
var http = require('http');
var otherfun = require("./modules/otherfuns.js")
http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (request.url !== "/favicon.ico") { //清除第2此访问
fun1(response)
otherfun.fun2(response)
// 用字符串调用对应函数
otherfun['fun3'](response)
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//---普通函数
function fun1(res) {
console.log("fun1")
res.write("你好,我是fun1");
}
网友评论