Home > Blockchain >  EADDRINUSE: address already in use when adding require
EADDRINUSE: address already in use when adding require

Time:07-21

On request my server should execute a cmd command and deploy.js file. Everything works fine, but if I add this line const { getSimpleMessage } = require('../src/server') I get the error that port 3000 is already in use. Why is this happening?

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);
   });

I run the file with command: node src/server.

CodePudding user response:

When you run require('../src/server'); in deploy.js file, all code of the src/server.js part is run, including the part app.listen(3000, ...). If the server is already running (using node src/server.js command) the port 3000 is already in use and running deploy.js (and thus attempting to run app.listen(3000, ...)) results in an error.

The simplest solution would be to separate the logic. If you want to keep both the getSimpleMessage and app declarations in the src/server.js file, you can remove the app.listen part from the file and instead export the app object. Then create e.g index.js file that imports the app object and runs the app.listen part.

./index.js:

const { app } = require('./src/server');

// starting the server
app.listen(3000, () => {
    console.log('listening on port 3000');
});

However, I would suggest that more clean solution would be to just put getSimpleMessage function in a separate file (if possible).

CodePudding user response:

When the server is running and receives a POST / request, it deploys Deploy.js, which causes the

app.listen(3000, ...)

command in server.js to be executed again, in another process. There would then be two processes both listening to port 3000, which leads to the observed error.

Perhaps you need to separate the getSimpleMessage function out of the server.js file.

  • Related