nodejs如何调用函数? - 网站

nodejs如何调用函数?

分类:Node.js常见问题 · 发布时间:2019-08-03 16:04 · 阅读:2177

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


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

浏览器中显示如下:

1 (2).jpg-600

控制台中显示如下:

2.jpg-600

标签:
nodejs

相关文章

如何设置 nodejs 的环境变量

在前端开发过程中,我们需要对 application 运行的环境进行设置,一般会包括开发环境development,生产环境production,每个环境可以对应不同的一些配置,例如不同环境下请求的地址...

谈谈Node.js与JavaScript的差异

Javascript是一种web前端语言,主要用于web开发中,由浏览器解析执行。Node.js是一个可以快速构建网络服务及应用的平台,是用Javascript语言构建的服务平台。

npm install安装报错怎么解决?

解决方法:1、报“operation not permitted”错误,通过“npm i 包名 --no-optional”解决;2、报“Missing: chromedriver”错误,表示没有安装chromedriver,安装一下即可。

怎么使用npm下载vue.js?

使用npm下载vue.js的方法:1、安装node.js和npm;2、安装cnpm;3、使用命令cnpm install -g vue-cli来安装即可。

vue.js和node.js是什么关系?

vue.js和node.js并没有关系,vue.js是前端框架,算是js的三大框架之一吧,node.js是后端开发语言,同php、java、c#一样的。但是他们可以配合使用。

返回分类 返回首页