node函数怎么被调用? - 网站

node函数怎么被调用?

分类:Node.js常见问题 · 发布时间:2019-09-05 16:30 · 阅读:1701

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

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

运行结果:

1 (2).jpg-600

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

运行结果:

2.jpg-600

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

运行结果:

3.jpg-600

标签:
node

相关文章

如何设置 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#一样的。但是他们可以配合使用。

返回分类 返回首页