根据请求,我的服务器应该执行cmd命令和deploy.js文件。一切都很好,但如果我添加这行const { getSimpleMessage } = require('../src/server')
,我会得到端口3000已经在使用的错误。为什么会发生这种情况?
Server.js:
app.post("/", (req,res) =>{
console.log("Get from /");
SimpleMessage = 'Hello world';
exec('npx hardhat run scripts/deploy.js --network goerli',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log("v error")
console.log(`exec error: ${error}`);
}
});
res.send("Server received the request");
});
// starting the server
app.listen(3000, () => {
console.log('listening on port 3000');
});
Deploy.js:
const { getSimpleMessage } = require('../src/server'); //THIS LINE CAUSES ERROR
async function main() {
const HelloWorld = await ethers.getContractFactory("HelloWorld");
// Start deployment, returning a promise that resolves to a contract object
const hello_world = await HelloWorld.deploy("HelloWorld");
console.log("Contract deployed to address:", hello_world.address);
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
我使用命令运行该文件:node-src/server。
在deploy.js
文件中运行require('../src/server');
时,会运行src/server.js
部件的所有代码,包括部件app.listen(3000, ...)
。如果服务器已经在运行(使用node src/server.js
命令(,则端口3000已经在使用,并且运行deploy.js
(从而尝试运行app.listen(3000, ...)
(会导致错误。
最简单的解决方案是将逻辑分离。如果要在src/server.js
文件中保留getSimpleMessage
和app
声明,则可以从文件中删除app.listen
部分,转而导出app
对象。然后创建例如index.js
文件,该文件导入app
对象并运行app.listen
部分。
./index.js
:
const { app } = require('./src/server');
// starting the server
app.listen(3000, () => {
console.log('listening on port 3000');
});
然而,我建议更干净的解决方案是将getSimpleMessage
函数放在一个单独的文件中(如果可能的话(。
当服务器正在运行并收到POST /
请求时,它会部署Deploy.js
,这会导致
app.listen(3000, ...)
server.js
中的命令在另一个过程中再次执行。然后将有两个进程都在侦听端口3000,这将导致观察到的错误。
也许您需要将getSimpleMessage
函数从server.js
文件中分离出来。