Home > front end >  node.js: send the output of stdout as response
node.js: send the output of stdout as response

Time:06-09

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

CodePudding user response:

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