Get Salesforce ContentVersion file info using node-fetch

Reading Time: < 1 minutes

Let’s say you want to get the file info without downloading it. For example, you want to know the file name and extension.
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 = "https://myinstance-dev-ed.my.salesforce.com";
    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 get the file info with node-fetch
      
const getFileInfo = async (conn, salesforceFileId, salesforceApiVersion) => {
    const url = `${conn.instanceUrl}/services/data/v${salesforceApiVersion}/sobjects/ContentVersion/${salesforceFileId}`;
    const ops = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'OAuth '+conn.accessToken
        }
    };
    const res = await fetch(url, ops);

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

    const json = await res.json();
    return {
        fileTitle: json.Title,
        fileName: `${json.Title}.${json.FileExtension}`,
        fileExtension: json.FileExtension,
        fileId: salesforceFileId,
    };
}
      
    
If you want to download the file without using node-fetch see
https://www.javaniceday.com/post/salesforce-rest-api-download-contentversion

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: