nodejs:为什么require中的module.exports=tesdf()只在get请求中执行一次



index.js

'use strict'
const express = require('express')
const app = express()
app.get('/', (req, res, next) => {
require('./test.js') // after repeated request is not executed
console.log("test")//after repeated request is  executed
next();
})
app.listen(8097)

test.js

function tesdf(){console.log("Gtest test", ind++); }
module.exports = tesdf()

如何再次调用函数。非常感谢。

导出文件时,需要导出函数、类或变量。这里是导出tesdf()函数的结果。要解决这个问题,只需将其导出为:

function tesdf(){console.log("Gtest test", ind++); }
module.exports = tesdf

此外,您不应该在get请求中使用required('./test.js'),因为每当某个客户端请求该端点时,该方法都会加载该文件。例如

let test = require('./test.js');
app.get('/', (req, res, next) => {
test();//Call the method
console.log("test")//after repeated request is  executed
next();
})

在NodeJS中导出模块会使其成为singleton,因此使其成为非singleton的一个选项是创建不同的实例:

test.js

function tesdf(){
console.log("Gtest test", ind++); 
}
module.exports = tesdf;

index.js

new (require('./test.js'))();

尝试在不运行的情况下导出函数,例如:

module.export = testdf

在以这种方式导出之前,请导入一个变量并运行。

const testdf = require('./test.js')
testdf()

test.js

function tesdf() {
console.log("Gtest test", ind++); 
}
module.exports = tesdf;

index.js

var test = require('/path/to/test.js');
test();

最新更新