gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:01:45 28 4
gpt4 key购买 nike

我是 JS 的新手,正在尝试将代码分成多个模块。我正在运行 nodejs,我很困惑为什么它会提示未定义路径检查器。有什么想法吗?

<

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 未定义

最佳答案

您需要将文件作为模块导出和导入。你这样做是这样的:

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

module.exports = A;

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

请注意,名称 A 在导入时是任意的,您可以随意命名。您还可以导出带有函数的对象而不是单个函数,然后在导入时可以从中获取属性。通过这种方式,您可以从单个文件中导出多个函数或值。

关于javascript - 如何在 node.js 中从一个文件调用 JS 函数到另一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107985/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com