Download a Salesforce ContentVersion file using node-fetch

Download locally a file stored in Salesforce using node-fetch package for Node.js

Andres Canavesi
Jul 07, 2022
Let's download a file (ContentVersion) from Salesforce using node-fetch
featured image
Let's download a file (ContentVersion) from Salesforce using node-fetch
The way to do it is to make a request to:
First, let's have a method to get the access token
const getJsForceConnection = async () => {
    const username = "******";
    const password = "******";
    const securityToken = "******";

    const salesforceUrl = "";
    const salesforceApiVersion = "52.0";

    const options = {instanceUrl: salesforceUrl, loginUrl: salesforceUrl, version: salesforceApiVersion};
    const conn = new jsForce.Connection(options);
    await conn.login(username, password + securityToken);

    return conn;
And then let's make a request to download the file using node-fetch
const downloadFile = async (conn, salesforceApiVersion, fileId) => {
    const url = `${conn.instanceUrl}/services/data/v${salesforceApiVersion}/sobjects/ContentVersion/${fileId}/VersionData`;
    const ops = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/octet-stream',
            'Authorization': 'OAuth '+conn.accessToken

    const fileFullPath = `${os.tmpdir()}/file.txt`; // probably you will need a random file here and also to know the file extension
    const res = await fetch(url, ops);
    const fileStream = fs.createWriteStream(fileFullPath);

    if(!res.ok) throw new Error(`error downloading file from ${url} status code: ${res.status} status message ${res.statusText}`);

    await new Promise((resolve, reject) => {
        res.body.on("error", reject);
        fileStream.on("finish", resolve);