Module.exports返回undefined:导出变量后require获取值异常求助
问题:导出变量后用require获取到undefined
我尝试从一个文件导出变量,但在另一个文件中使用require获取时得到undefined,怀疑是函数导致的问题,但不知道怎么修复。
涉及代码文件
Index.js
app.post("/", (req,res) =>{ console.log("Get from /"); module.exports.SimpleMessage = 'Hello world'; // 导出变量 exec('npx hardhat run scripts/deploy.js --network goerli', (error, stdout, stderr) => { if (error !== null) { console.log(`exec error: ${error}`); } }); res.send("Server received the request"); }); // 启动服务器 app.listen(3000, () => { console.log('listening on port 3000'); });
Deploy.js(完整版本)
async function main() { const HelloWorld = await ethers.getContractFactory("HelloWorld"); var msg = require('../src/index.js'); // 引入变量 console.log(msg.SimpleMessage); const hello_world = await HelloWorld.deploy(); } main() .then(() => process.exit(0)) .catch(error => { console.error(error); process.exit(1); });
问题原因及修复方案
核心问题
- 模块加载时机不匹配:Node.js的
require是同步加载且会缓存模块。当deploy.js执行require时,index.js里的app.post回调还没触发(只有收到POST请求时才会执行),此时module.exports.SimpleMessage根本没被赋值,所以返回undefined。 - 进程完全隔离:你用
exec启动了一个独立的Hardhat进程来运行deploy.js,这个进程和Node.js服务器进程的内存空间完全不共享,就算POST回调里赋值了变量,另一个进程也拿不到。
可行修复方案
方案1:通过命令行参数传递数据
在index.js执行exec时,把变量作为命令行参数传给deploy.js:
// 修改Index.js中的exec部分 exec(`npx hardhat run scripts/deploy.js --network goerli --message "Hello world"`, (error, stdout, stderr) => { if (error !== null) { console.log(`exec error: ${error}`); } });
然后在deploy.js里解析命令行参数:
async function main() { const HelloWorld = await ethers.getContractFactory("HelloWorld"); // 提取命令行参数中的消息 const msgIndex = process.argv.indexOf('--message'); const SimpleMessage = msgIndex !== -1 ? process.argv[msgIndex + 1] : '默认消息'; console.log(SimpleMessage); const hello_world = await HelloWorld.deploy(); }
方案2:通过临时文件传递(适合复杂数据)
如果要传递的数据结构复杂,用临时文件更合适:
- 在
index.js的POST回调里写入临时文件:
const fs = require('fs'); const path = require('path'); app.post("/", (req,res) =>{ console.log("Get from /"); const messageData = {SimpleMessage: 'Hello world'}; // 写入临时JSON文件 fs.writeFileSync(path.join(__dirname, 'temp-data.json'), JSON.stringify(messageData)); exec('npx hardhat run scripts/deploy.js --network goerli', (error, stdout, stderr) => { if (error !== null) { console.log(`exec error: ${error}`); } // 可选:执行完成后删除临时文件 fs.unlinkSync(path.join(__dirname, 'temp-data.json')); }); res.send("Server received the request"); });
- 在
deploy.js里读取临时文件:
const fs = require('fs'); const path = require('path'); async function main() { const HelloWorld = await ethers.getContractFactory("HelloWorld"); // 读取临时文件内容 const tempFilePath = path.join(__dirname, '../src/temp-data.json'); const msgData = JSON.parse(fs.readFileSync(tempFilePath, 'utf8')); console.log(msgData.SimpleMessage); const hello_world = await HelloWorld.deploy(); }
内容的提问来源于stack exchange,提问作者Nina
相关产品推荐
相关产品推荐

