Download a Salesforce ContentVersion file using node-fetch

Download a Salesforce ContentVersion file using node-fetch
Reading Time: < 1 minute

Salesforce content management allows users to store information such as documents, images, audio, and video files in their Salesforce org. On occasion, users may require to quickly and easily download certain content items from the Salesforce org using their own custom code.

Node-fetch is a popular Node.js library used by developers to create applications with the help of middleware, through a programming interface. Node-fetch is especially suitable for downloading Salesforce ContentVersion files.

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);

, ,

About the author

Andrés Canavesi
Andrés Canavesi

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

Join 22 other subscribers

One response to “Download a Salesforce ContentVersion file using node-fetch”

Leave a Reply