Search code examples
node.jsfiledownloadgetsynchronous

How to download file from gitlab synchronously using NodeJS


I need to download a file from a private gitlab server and I need the method to be synchronous. This was by previous async code and it works fine because I was using promises. But I'm having trouble converting it to synchronous. The other posts i've seen on SO either ended up using async code or didn't have options for headers.

            const https = require('https');
            const fs = require('fs');
            const gitlabUrl = 'https://gitlab.custom.private.com';
            const gitlabAcessToken = 'xmyPrivateTokenx';
            const gLfilePath = '/api/v4/projects/1234/repository/files/FolderOne%2Ftest.txt/raw?ref=main';
            const gLfileName='test.txt';
            
                
            function downloadFileFromGitlab(filePath, fileName) {
                    return new Promise((resolve, reject) => {
                        var options = {
                            path: filePath,
                            headers: {
                                'PRIVATE-TOKEN': gitlabAccessToken
                            }
                        };
                        
                        var url = gitlabUrl
                        var file = fs.createWriteStream(fileName);
                        
                        const request = https.get(url, options, (response) => {
                            response.pipe(file);
                            file.on('finish', () => {
                                file.close();
                                resolve();
                            });
                            file.on('error', (err) => {
                                file.close();
                                reject(err);
                            });
                        });
                
                        request.on('error', error => {
                            throw console.error(error);
                        });
                    });
                }

downloadFileFromGitlab(gLfilePath,gLfileName);

Solution

  • I was able to figure it out using curl

    function downloadFileFromGitlab(filePath, fileName) {
        let curlCommand = "curl -s " + gitlabUrl + filePath + " -H 'PRIVATE-TOKEN:" + gitlabAccessToken +"'";
        let file = child_process.execSync(curlCommand);
        fse.writeFileSync(fileName,file);
    }