美文网首页程序员今日看点
node.js 学习二 之 函数调用

node.js 学习二 之 函数调用

作者: skuare520 | 来源:发表于2016-12-24 11:27 被阅读235次

    本地函数

    var http = require('http');
    http.createServer(function(request, response) {
        response.writeHead(200, { 'Content-Type': 'text/html;    charset=utf-8' });
        if (request.url !== "/favicon.ico") { //清除第2此访问  
            fun1(response)
            response.end('');
        }
    }).listen(8000);
    console.log('Server running at http://127.0.0.1:8000/');
    //---普通函数      
    function fun1(res) {
        console.log("fun1")
        res.write("你好,我是fun1");
    }
    

    浏览器:

    02_fun1_chrome.png

    控制台:

    02_fun1_console.png

    调用另外一个js文件的函数

    1.同级目录下新建文件夹modules,进入文件夹新建一个文件

    │  02_funcall.js
    └─ modules
            └─otherfuns.js
    

    2.otherfuns.js

    function fun2(res) {
        console.log("fun2")
        res.write("hello, 我是fun2")
    }
    
    // 如果要声明为可被外部调用的
    module.exports = fun2
    

    3.修改原来的02_funcall.js

    var http = require('http');
    var otherfun = require("./modules/otherfuns.js")
    
    http.createServer(function(request, response) {
        response.writeHead(200, { 'Content-Type': 'text/html;    charset=utf-8' });
        if (request.url !== "/favicon.ico") { //清除第2此访问  
            fun1(response)
            otherfun(response)
            response.end('');
        }
    }).listen(8000);
    console.log('Server running at http://127.0.0.1:8000/');
    //---普通函数      
    function fun1(res) {
        console.log("fun1")
        res.write("你好,我是fun1");
    }
    

    浏览器:

    02_fun2_chrome.png

    控制台:

    02_fun2_console.png

    导出多个函数

    otherfuns.js

    //支持多个函数      
    module.exports = {
        getVisit: function() {
            return visitnum++;
        },
        add: function(a, b) {
            return a + b;
        },
        fun2: function(res) {
            console.log("fun2")
            res.write("hello, 我是fun2")
        },
        fun3: function(res) {
            console.log("fun3")
            res.write("hello, 我是fun3")
        }
    }
    

    02_funcall.js

    var http = require('http');
    var otherfun = require("./modules/otherfuns.js")
    
    http.createServer(function(request, response) {
        response.writeHead(200, { 'Content-Type': 'text/html;    charset=utf-8' });
        if (request.url !== "/favicon.ico") { //清除第2此访问  
            fun1(response)
            otherfun.fun2(response)
            // 用字符串调用对应函数
            otherfun['fun3'](response)
            response.end('');
        }
    }).listen(8000);
    console.log('Server running at http://127.0.0.1:8000/');
    //---普通函数      
    function fun1(res) {
        console.log("fun1")
        res.write("你好,我是fun1");
    }
    

    相关文章

      网友评论

        本文标题:node.js 学习二 之 函数调用

        本文链接:https://www.haomeiwen.com/subject/gjplvttx.html