如何在Expressjs或Nodejs中使用常规Javascript变量
有没有一种方法可以从常规javascript导出变量以用于expressjs 我尝试过使用“导出”,但不起作用 例如,在常规js文件中如何在Expressjs或Nodejs中使用常规Javascript变量,javascript,node.js,express,Javascript,Node.js,Express,有没有一种方法可以从常规javascript导出变量以用于expressjs 我尝试过使用“导出”,但不起作用 例如,在常规js文件中 var search ='hello'; exports= search; 然后在express文件中 var search= require("./file.js"); console.log(search); 我在控制台中得到的只是“{}” 我希望变量“search”也能在我的express文件中工作。有没有办法做到这一点欢迎来到StackOverflo
var search ='hello';
exports= search;
然后在express文件中
var search= require("./file.js");
console.log(search);
我在控制台中得到的只是“{}”
我希望变量“search”也能在我的express文件中工作。有没有办法做到这一点欢迎来到StackOverflow!要导出文件1中的变量,请执行以下操作:
var search = 'hello'
export search
// OR
export var search = 'hello'
import * as someName from './file1'
someName.search
// OR
var someName = require('./file1')
someName.search
要将其导入文件2中,请执行以下操作:
var search = 'hello'
export search
// OR
export var search = 'hello'
import * as someName from './file1'
someName.search
// OR
var someName = require('./file1')
someName.search
请在此处阅读更多信息:请参阅文档中的:
exports
变量在模块的文件级范围内可用,并在评估模块之前分配module.exports
的值
但它也说:
但是,请注意,与任何变量一样,如果将新值分配给导出
,它将不再绑定到模块.exports
因此,当您执行exports=search
时,它不会被导出,只在模块中可用。要使其工作,只需将其更改为module.exports=search
相关:你做错了。以下是正确的方法: 走错了路
var search ='hello';
exports= search;
var search = 'hello';
exports.search = search;
正确的方法
var search ='hello';
exports= search;
var search = 'hello';
exports.search = search;
称之为
var { search } = require('./file.js')
console.log(search)
我希望我的答案是清楚的,祝你好运