How to download a Salesforce file from Node.js

Reading Time: < 1 minutes

index.js

      
const jsforce = require('jsforce');
const https = require('https');
const fs = require('fs');
const conn = new jsforce.Connection();
const userName = '*******';
const password = '*******';
const securityToken = '*********';
const fileId = '0684W00000BzWohQAF';
const fullFileName = '/Users/andrescanavesi/sf.png';

conn.login(userName, password+securityToken, function(err, res) {
    if (err) { return console.error(err); }

    console.log(conn.accessToken);
    console.log(conn.instanceUrl);
    // logged in user property
    console.log("User ID: " + res.id);
    console.log("Org ID: " + res.organizationId);

    downloadFile(conn);

});

function downloadFile(conn) {

    const options = {
        hostname: 'myinstance-dev-ed.my.salesforce.com',
        port: 443,
        path: '/services/data/v51.0/sobjects/ContentVersion/'+fileId+'/VersionData',
        method: 'GET',
        headers: {
            'Content-Type': 'application/octet-stream',
            'Authorization': 'OAuth '+conn.accessToken
        }
    }

    https.get(options, (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log('chunk');
            data += chunk;

            fs.appendFile(fullFileName, chunk, function (err) {
                if (err) throw err;
                console.log('chunk updated');
            });

        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log('data downloaded');
        });

    }).on("error", (err) => {
        console.log("Error: " + err.message);
    });
}

      
    

package.json


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: