Hello community! I’m very new to DatoCMS and not yet too familiar with Node-JS.
I want to download media files (uploads) that fit a certain filter (file-extension, in-use) to the local file system in order to run some checks on them.
I’ve seen the docs about exporting and was wondering how I would have to change that example to fit my needs. If anyone has a snippet or can point me in the right direction, I would highly appreciate it.
It can be with the node-js client or in Python using the requests package.
Thanks!
This should work!
const { SiteClient } = require('datocms-client');
const got = require('got');
const { basename } = require('path');
const { createWriteStream } = require('fs');
(async () => {
try {
const client = new SiteClient(
'YOUR_API_TOKEN',
);
const uploads = await client.uploads.all(
{
filter: { fields: { in_use: { eq: true }, format: { eq: 'png' } } },
},
{ allPages: true },
);
for (const upload of uploads) {
await new Promise((resolve, reject) => {
const localPath = basename(upload.path);
console.log(`Downloading ${upload.url} to ./${localPath}...`);
const downloadStream = got.stream(upload.url);
const fileWriterStream = createWriteStream(localPath);
downloadStream
.on('downloadProgress', ({ transferred, total, percent }) => {
const percentage = Math.round(percent * 100);
console.error(`progress: ${transferred}/${total} (${percentage}%)`);
})
.on('error', reject);
fileWriterStream
.on('error', reject)
.on('finish', () => {
console.log(`File downloaded to ${localPath}`);
resolve();
});
downloadStream.pipe(fileWriterStream);
});
}
} catch (e) {
console.log(e);
}
})();
1 Like
That works perfectly! Thank you so much for the helpful example!