1
const express = require('express');
const { stdout } = require('process');

const router = express.Router();

router.get('/', (req, resp) => {
  var exec = require('child_process').exec;

  exec(
    'npx hardhat run scripts/deploy-contract.mjs --network PolygonMumbai',
    function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }
    }
  );

  const smartcontract = stdout.toString().substring(30, 72);
  console.log(smartcontract);
  resp.send(smartcontract);
});

I am a beginner with request-response and solidity. But what I am trying to do is deploying a contract through command line execution and sending the output as a response. Basically, I want to build an API that when called deploys the smart contract and sends the response as the smartcontract address. Currently I am not able to send the string as response.

Also please let me know if this is the right way to do this

1 Answer 1

2

I believe you just need to write the response in the exec callback:

router.get('/', (req, resp)=>{
    
   var exec = require('child_process').exec;

   exec('npx hardhat run scripts/deploy-contract.mjs --network PolygonMumbai',
    function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
             console.log('exec error: ' + error);
        }

       const smartcontract = stdout.toString().substring(30,72);
       console.log(smartcontract);
       resp.send(smartcontract)
    });
})
Sign up to request clarification or add additional context in comments.

5 Comments

hey could you please explain a bit more, i put the exec inside resp.send(), it did not work. I need a string as the output, thanks for the reply!
What's the error you're getting?
so i did this resp.send(exec( 'npx hardhat run scripts/deploy-contract.mjs --network PolygonMumbai', function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } } ).toString()); --- on the screen i get -- [object Object]
Sorry for my previous comments ! it worked the solution you sent!! thanks :)
Great to hear! Best of luck

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.