Salesforce rest api download ContentVersion

Download a Salesforce file (ContentVersion) through the API using Node.js with jsforce package


Sep 09, 2021
featured image

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

      
{
  "name": "salesforce-api-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jsforce": "^1.10.1"
  }
}

      
    

Run it

node index.js
nodejs salesforce contentversion