简体   繁体   English

Node.js 中的“类型错误:不是函数”

[英]'TypeError: is not a function' in Node.js

I'm getting the error while running the following code in Node.js在 Node.js 中运行以下代码时出现错误

var assert = require('assert');
var request = require('request');
var index = require('./index');
it('verify javascript function', function(done) {
    var v2 = index.AddNumbers(5, 6);
    assert.equal(11, v2);
    done();
});

The index.js file contain the following code: index.js文件包含以下代码:

function AddNumbers(a,b){
    return a+b;
}

What am I doing wrong?我究竟做错了什么?

由于循环依赖,这种情况在我身上发生过很多次,检查您是否有 2 个相互需要的类,将其中一个从要求另一个中删除,问题应该得到解决

With NodeJS modules , to make something public, you have to export it.使用 NodeJS模块,要公开某些内容,您必须将其导出。 Add this to the end of index.js :将此添加到index.js的末尾:

module.exports.AddNumbers = AddNumbers;

Here it is running on my machine:它在我的机器上运行:

$ cat index.js 
function AddNumbers(a,b){
    return a+b;
}

module.exports.AddNumbers = AddNumbers;

$ cat example.js 
var index = require('./index');
var v2 = index.AddNumbers(5,6);
console.log(v2);

$ node example.js
11

I'm fairly a beginner at Node JS so I managed to get this error by importing a function like so:我是 Node JS 的初学者,所以我通过导入这样的函数设法得到了这个错误:

const { functionName } = require('./function')

instead of like so:而不是这样:

const functionName = require('./function')

Editing my post to add an explanation since I've learned more node since I wrote it.编辑我的帖子以添加解释,因为自从我写它以来我学到了更多的节点。 If a module exports an object containing multiple functions functions like so:如果一个模块导出一个包含多个函数的对象,如下所示:

module.exports = { functionName, otherFunction }

Then the function has to be deconstructed out of the object during the import, as in the first code snippet.然后必须在导入期间从对象中解构函数,如第一个代码片段所示。 If the module exports a single function or a default function, like so:如果模块导出单个函数或默认函数,如下所示:

 module.exports = functionName

Then tt must be imported directly, as in the second code snippet.然后 tt 必须直接导入,如第二个代码片段所示。

If you need to expose a specific component, function or a variable to public.如果您需要向公共公开特定的组件、函数或变量。 You have to exports those components using JavaScript modules.您必须使用 JavaScript 模块exports这些组件。

let add = (a,b)=>{
    return ( a+b);
}
module.exports.add=add;

or if you want to expose multiple functions, you can do as follows.或者如果你想暴露多个函数,你可以这样做。

let add = (a,b)=>{
    return (a+b);
}
let subtract = (a, b)=>{
    return (a-b);
}
module.exports={
   add : add,
   subtract : subtract
};

发生这种情况是因为两个文件相互引用,即您正在从文件 B 中的文件 A 调用函数,反之亦然,这称为循环依赖。

Your "AddNumbers" function in the "index.js" file should be as follows, “index.js”文件中的“AddNumbers”函数应如下所示,

function AddNumbers(a,b){
    var addition = function(a, b){
      return (a + b) ;
    };

    module.exports = {
       additionResult: addition
    };
}

And you need to call it in your "Node.js" file as follows你需要在你的“Node.js”文件中调用它,如下所示

var assert = require('assert');
var request = require('request');
var index = require('./index');
it('verify javascript function', function(done) {
    var v2 = index.additionResult(5, 6);
    assert.equal(11, v2);
    done();
});

This should work.这应该有效。 Please note that you call the function by whatever the token name you exported the return value by (I use a different name here just for clarity).请注意,您通过导出返回值的任何令牌名称调用该函数(为了清楚起见,我在这里使用了不同的名称)。 Almost everybody uses the same name as the function name so there are no confusion.几乎每个人都使用与函数名称相同的名称,因此不会混淆。 Also in ES6, if you use the same name you can export as just,同样在 ES6 中,如果您使用相同的名称,则可以导出为,

module.exports = {
       addition
};

instead of,代替,

module.exports = {
       addition: addition
};

since you use the same name.因为您使用相同的名称。 It is an ES6 feature.这是一个 ES6 特性。

I ran into the same problem while trying to follow a Nodejs tutorial by w3schools.我在尝试学习 w3schools 的 Nodejs 教程时遇到了同样的问题。 I copied the following code from them:我从他们那里复制了以下代码:

exports.myDateTime = function () {
return Date();
};

That, however, wouldn't work for me.然而,这对我不起作用。 What resolved the problem for me was adding module.对我来说解决问题的是添加module. before the exports keyword like this:在这样的导出关键字之前:

module.exports.myDateTime = function () {
return Date();
};

https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de

this post visualizes the circular dependency injection like a child or nested file tried to import parent or top-level file这篇文章将循环依赖注入可视化,就像尝试导入父文件或顶级文件的子文件或嵌套文件一样

repo.js repo.js

service.js服务.js

there are 2 files有2个文件

service.js uses repo.js file by importing it works but check in repo.js that it tried to import service.js file it shows circular dependency injection warning service.js 通过导入来使用 repo.js 文件,但在 repo.js 中检查它试图导入 service.js 文件它显示循环依赖注入警告

The most correct answer was from @shimi_tap.最正确的答案来自@shimi_tap。 I want to reply it as comment, but doesn't have enough reputation, so I am gonna answer it using a simple example, like in this case below:我想以评论的形式回复它,但没有足够的声誉,所以我将使用一个简单的例子来回答它,如下面的例子:

  1. File A has 3 functions to process database activity: function addDB , updateDB , and delData ;文件 A 有 3 个函数来处理数据库活动: function addDBupdateDBdelData
  2. File B has 2 functions to process User activity on smartphone: function addHistory , and editHistory ;文件 B 有 2 个函数来处理智能手机上的用户活动: function addHistoryeditHistory

Function updateDB in file A is calling function editHis in file B, and function editHistory is calling function updateDB in file A. This is what we called circular-dependency. Function updateDB in file A is calling function editHis in file B, and function editHistory is calling function updateDB in file A. This is what we called circular-dependency. And we need to prevent it by only giving output of state from editHistory and the rest will be processed inside file A.我们需要通过仅从editHistory给出state的editHistory和rest将在文件A中处理来防止它。

 //ORIGINAL FUNCTIONS which caused CIRCULAR DEPENDENCY function updateDB() { //process update function here //call function in fileB const history = require("fileB.js"); await history.editHistory(data).then((output) => { if(output["message"] === "success"){ response = { state: 1, message: "success", }; } }); return response; } //THIS is the WRONG ONE function editHistory() { //process function to edit History here //call function in fileA const file = require("fileA.js"); await file.updateDB(data).then((output) => { //You should not call it here if(output["message"] === "success") { output = { state: 1, message: "success", }; } }); return output; } //==================================================// //THE FIX function updateDB() { //process function here const history = require("fileB.js"); await history.editHistory(data).then((output) => { if(output["message"] === "success"){ await updateDB(data).then((output) => { response = { state: 1, message: "success", }; }); } else { log("Error"); } }); return response; } function editHistory() { //process function to edit History here // No more calling to function inside the file A output = { state: 1, message: "success", }; return output; }

A simple way I debugged this (After about 2 days of troubleshooting) was to actually see why 'x' is not a function.我调试这个的一个简单方法(经过大约 2 天的故障排除后)是真正了解为什么“x”不是一个函数。 Basically, console.log(x) to see the actual object returned.基本上, console.log(x) 查看返回的实际对象。 Turned out I was conflicting x with another declared variable (happens especially when you use axios.res and req,res args.结果我与另一个声明的变量发生了冲突(尤其是当你使用 axios.res 和 req,res args 时。

just pass the function as an argument it will solve your Problem只需将函数作为参数传递即可解决您的问题

now you can access the sample function without having to require it in sample2 file this solves the problem of typeError现在您可以访问示例函数而无需在 sample2 文件中要求它,这解决了 typeError 的问题

//sample 
const sample2 = require('./sample2');
const sample = async (payload) => {
  const { value }= payload;
  const response = sample2({sample});
}


// sample2
const sample2 = async ({sample}) => {
  const response = sample({value});
}
module.exports = sample2;
  

One silly mistake I did was while exporting was:我在导出时犯的一个愚蠢的错误是:

module.exports = [module_name_1, module_name_2, ..., module_name_n]

The right way is:正确的方法是:

module.exports = {module_name_1, module_name_2, ..., module_name_n}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM