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.
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;
}
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.pipe(fileStream);
res.body.on("error", reject);
fileStream.on("finish", resolve);
});
}