1.同一个文件夹中的方法调用
const http = require('http'); //导入http const hostname = '192.168.1.108'; //ip地址 随便写 如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址 const port = 3000; //端口号 const server = http.createServer((req, res) => { //创建一个server res.statusCode = 200; res.setHeader('Content-type', 'text/plain;charset = utf-8'); if (req.url !== '/favicon.ico') { //清除二次访问 re(res); //同一个文件下的方法调用 res.end(); //用于关闭连接 } }); server.listen(port, hostname, () => { //监听server console.log(`服务器运行在http://${hostname}:${port}/`); }); function re(response) { response.write('hello world!!!'); }
2.不同文件下的方法调用
首先在outer_fun_demo.js 中定义方法,并用module.exports导出
function fun1(response) { response.write('我是fun1'); } function fun2(response) { response.write('我是fun2'); } // module.exports = fun1; //导出单个方法 module.exports = { //导出一个对象 fun1, fun2 }
在哪要用outer_fun_demo.js 中定义方法,就在哪用require导入即可
const funs = require('./outer_fun_demo.js'); //导入外部文件 const http = require('http'); //导入http const hostname = '192.168.1.108'; //ip地址 随便写 如需要在局域网内,用手机访问,则需要将其设置为电脑的ipv4地址 const port = 3000; //端口号 const server = http.createServer((req, res) => { //创建一个server res.statusCode = 200; res.setHeader('Content-type', 'text/plain;charset = utf-8'); if (req.url !== '/favicon.ico') { //清除二次访问 //当funs是单个方法时: // funs(res); //调用外部文件中的方法 //当funs是个对象时: funs.fun1(res); res.end(); //用于关闭连接 } }); server.listen(port, hostname, () => { //监听server console.log(`服务器运行在http://${hostname}:${port}/`); });