js的函数怎么被调用到html,node函数怎么被调用?

简单的说 Node.js 就是运行在服务端的 JavaScript。Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。下面我们来看一下node中怎么函数怎么调用。

d4af972e51bff15206de403dd47d53b7.png

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/');

运行结果:

da16f3abd25018e39f7680f48964427f.png

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;//只能引用一个函数

运行结果:

f43b5719b640e02a03d65264cb12f3b7.png

在这个例子中我们成功调用了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")

}

}

运行结果:

cd5d566df4e511b7d52553e0790bf4e1.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值