如何在node.js中从一个文件调用JS函数到另一个文件?

时间:2017-09-08 03:00:14

标签: javascript node.js

我是JS新手并试图将代码分解为多个模块。我正在运行nodejs,我很困惑这里为什么抱怨 pathChecker没有定义。关于它的任何想法?

<

const http = require('http');
const parseUrl = require('parseurl');
const path = require('path');


http.createServer( function (req, res)
{
    try
    {

        // this is library function
        var pathName = decodeURIComponent(parseUrl(req));

        // create a literal validateFile to validate the path
        var validateFile = new pathChecker(pathName);

        // This is an engine to validate the path problems related to security, existence etc.
        validateFile.pathCheck();

        if(validateFile.error === true) {
            res.statusCode = validateFile.statusCode;
            res.end(validateFile.ErrorMsg);

            return;
        }

    }
    catch(err)
    {
        res.statusCode = err.status || 500;
        res.end(err.message);
    }

}).listen(4000);

我有另一个名为

的文件

errorHandler.js

function pathChecker(path)
{
    this.error = true;
    this.path = path;
    this.statusCode = 500;
    this.ErrorMsg = "Internal Server Error";
    this.pathCheck = function()
    {
        if(!path)
        {
            this.statusCode = 400;
            this.ErrorMsg = 'path required';
            this.error = true;
        }
        else{
            this.statusCode = 200;
            this.ErrorMsg = undefined;
            this.error = false;
        }
    }
};

运行时,我得到输出

未定义pathChecker

2 个答案:

答案 0 :(得分:2)

您需要将文件导出并导入为模块。你这样做:

// File A.js
function A() {
}

module.exports = A;

// File B.js
var A = require("./A");
A();

请注意,名称A在导入时是任意的,您可以根据需要命名。您还可以导出具有函数的对象而不是单个函数,然后在导入时可以从中获取属性。这样,您可以从单个文件中导出多个函数或值。

答案 1 :(得分:0)

您需要在errorHandler.js文件中导出该函数。

function pathChecker(path) {
  ...
}
module.exports = pathChecker;

然后导入,使用

将其导入主文件
const pathChecker = require("./errorHandler")