从同一个文件和不同的文件调用nodejs函数

calling nodejs function from the same file and from the different file

本文关键字:文件 调用 nodejs 函数 同一个      更新时间:2023-09-26

Model.js文件具有以下条目

exports.update = function(tag,view,date){
{
    .....
    ....
}

并调用类似的函数

 update('test','1213','11/10/2014')

它抛出以下错误,

update('test','1213','11/10/2014')
^
ReferenceError: update is not defined

我可以从不同的文件调用更新模块,没有任何错误,比如这个

var model =  require('./Model');
model.update('test','1213','2001/1/23')

问题是如何从相同的js(Model.js)文件

调用Update方法

在model.js 中

exports.update = function update(tag, view, date) { ... }
exports.update('red', 'colors', new Date())

如果您经常(像在循环中)调用方法,也可以考虑声明一个局部变量

var update = exports.update = function update(tag, view, date) { ... }
update('red', 'colors', new Date())

内部foo.js

var update = require('./model').update
update('yellow', 'colors', new Date())

从问题本身来看,还不清楚更新方法的作用和数据,所以如果你提供真实的代码,答案可能会有所调整。

您必须首先定义函数,然后像这样导出函数-

var update=function(tag,view,date){
......
}
module.exports={
  update:update
}

通过这样做,您可以从文件内部和外部访问"update()"函数。