Search code examples
node.jscurlchild-process

NodeJS exec - Getting progress data while running curl instead of api resonse


I am trying to run curl in exec using the below code.

const { exec } = require('child_process');

const shell = (cmd, errMsg) => {
    return new Promise((resolve, reject) => {
        exec(cmd, (error, stdout, stderr) => {
            if (error || stderr) {
                console.error(error || stderr);
                reject(errMsg ?? (error || stderr));
            }
            resolve(stdout);
        })
    })
}

const test = async (curlCmd) => {
    try {
        const stdout = await shell(curlCmd, 'curl failed');
        console.log(stdout);
    } catch (err) {
        console.error(err);
    }
}

test('curl -X GET "https://dummyapi.com/get-data?p1=abc&p2=def&" -H "Cache-Control: no-cache" -H "Content-Type: application/json"')

But instead of getting api response, some progress data is returned like below

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   188  100   188    0     0    274      0 --:--:-- --:--:-- --:--:--   276

If I hit the same command in terminal, i am getting the proper response.

Node Version: 14.19.1


Solution

  • Add -s flag to hide the progress bar:

    test('curl -s -X GET "https://dummyapi.com/get-data?p1=abc&p2=def&" -H "Cache-Control: no-cache" -H "Content-Type: application/json"')