html怎么调用node.js,nodejs如何调用函数?

本文详细介绍了在 Node.js 中如何调用函数,包括内部调用普通函数、调用外部单一函数以及调用外部多个函数。通过示例代码展示了如何使用 `module.exports` 导出和导入函数,以及如何在不同的场景下灵活调用这些函数。
摘要由CSDN通过智能技术生成

NodeJs中调用函数的方式有多种,可以在内部调用普通函数,还可以调用外部单个函数以及调用外部多个函数等。普通内部函数可以直接调用,外部函数需要先使用module.exports=fun将函数导出,然后就可以直接调用了。

27b66654b1ceea06b08c98c3096448bf.png

nodejs调用函数的方法如下:

一、内部调用普通函数

保存d2_function1.js,代码如下:var http = require('http');

http.createServer(function (req, res) {

res.writeHead(200, {'Content-type':'text/html; charset=utf-8'});

if (req.url !== '/favicon.ico') {

//调用普通内部函数

fun1(res);

console.log('ok....');

}

}).listen(3000);

console.log('running localhost:3000');

//普通内部函数

function fun1(res) {

res.write('test function....');

res.end();

}

二、调用外部单一函数

新建一个名为functions的文件夹,保存other_fun1.js,代码如下:function other_fun1(res) {

res.write('this is other_fun1...');

res.end();

}

//只能调用一个函数

module.exports = other_fun1;

保存d2_function2.js,代码如下:var http = require('http');

var other_fun1 = require('./functions/other_fun1');//引用外部文件

http.createServer(function (req, res) {

res.writeHead(200, {'Content-type':'text/html; charset=utf-8'});

if (req.url !== '/favicon.ico') {

//调用外部单个函数

other_fun1(res);

console.log('ok....');

}

}).listen(3000);

console.log('running localhost:3000');

三、调用外部多个函数

在functions文件夹中保存other_fun2.js,代码如下://导出多数函数供外部调用

module.exports = {

fun1:function (res) {

res.write('more functions..');

},

fun2:function (a, b) {

var sum = a + b;

return sum;

}

}

保存d2_function3.js,代码如下:var http = require('http');

//引入外部函数文件,调用多个函数

var o_func = require('./functions/other_fun2');

http.createServer(function (req, res) {

if (req.url !== '/favicon.ico') {

res.writeHead(200, {'Content-type':'text/html; charset=utf-8'});

console.log('ok...');

//调用函数1

o_func.fun1(res);

//调用函数2

console.log(o_func.fun2(3, 9));

//另一种方式调用函数

o_func['fun1'](res);

var fun_name = 'fun2';

console.log(o_func[fun_name](23, 9));

res.end();

}

}).listen(3000);

console.log('running localhost:3000');

cmd中运行 node d2_function3.js

浏览器中显示如下:

1fdc434c36a94eeb0f5e2b0d6f2a8d6a.png

控制台中显示如下:

f0dd3c4a27fde837f624f03e577cc239.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值