我是nodejs的新手。我有以下文件和代码:
// file: myfunc.js
function myfunc() { return "myfunc()"; }
exports = myfunc;
和
// file: index.js
var mf = require("./myfunc");
var mfunc = mf();
console.log(mfunc);
当我从命令行运行node index.js
时,我收到错误
var mfunc = mf()
^
TypeError: Object is not a function
为什么会出现此错误?我看到下面粘贴的其他人的代码,我尝试按照相同的方法尝试让require()
返回函数而不是对象。
// file: index.js from another app
var express = require('express');
var app = express();
require('express')
如何返回函数但require('./myfunc')
无法返回函数?
答案 0 :(得分:2)
应该是......
module.exports = myfunc;
......相反。引用the doc:
如果您希望模块导出的根是一个函数(例如 构造函数)或者如果要在一个中导出完整的对象 分配而不是一次构建一个属性,将其分配给
module.exports
代替exports
。