Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Expressjs或Nodejs中使用常规Javascript变量_Javascript_Node.js_Express - Fatal编程技术网

如何在Expressjs或Nodejs中使用常规Javascript变量

如何在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

有没有一种方法可以从常规javascript导出变量以用于expressjs

我尝试过使用“导出”,但不起作用

例如,在常规js文件中

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)
我希望我的答案是清楚的,祝你好运