58 lines
1.6 KiB
JavaScript
58 lines
1.6 KiB
JavaScript
|
|
const { MongoClient, GridFSBucket } = require('mongodb');
|
||
|
|
const fs = require('fs');
|
||
|
|
const path = require('path');
|
||
|
|
|
||
|
|
async function exportGridFS() {
|
||
|
|
const client = new MongoClient('mongodb://localhost:27017/');
|
||
|
|
|
||
|
|
try {
|
||
|
|
await client.connect();
|
||
|
|
const db = client.db('portfolio');
|
||
|
|
|
||
|
|
const buckets = ['images', 'album_art', 'scores', 'pubs'];
|
||
|
|
|
||
|
|
for (const bucketName of buckets) {
|
||
|
|
const bucket = new GridFSBucket(db, { bucketName });
|
||
|
|
const outputDir = path.join(__dirname, 'public', bucketName);
|
||
|
|
|
||
|
|
if (!fs.existsSync(outputDir)) {
|
||
|
|
fs.mkdirSync(outputDir, { recursive: true });
|
||
|
|
}
|
||
|
|
|
||
|
|
const cursor = bucket.find({});
|
||
|
|
const files = await cursor.toArray();
|
||
|
|
|
||
|
|
console.log(`Exporting ${files.length} files from ${bucketName}...`);
|
||
|
|
|
||
|
|
const promises = files.map(file => {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
const outputPath = path.join(outputDir, file.filename);
|
||
|
|
const stream = bucket.openDownloadStreamByName(file.filename);
|
||
|
|
const writeStream = fs.createWriteStream(outputPath);
|
||
|
|
|
||
|
|
stream.pipe(writeStream);
|
||
|
|
|
||
|
|
stream.on('end', () => {
|
||
|
|
console.log(` Saved: ${file.filename}`);
|
||
|
|
resolve();
|
||
|
|
});
|
||
|
|
|
||
|
|
stream.on('error', (err) => {
|
||
|
|
console.error(` Error saving ${file.filename}:`, err.message);
|
||
|
|
reject(err);
|
||
|
|
});
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
await Promise.all(promises);
|
||
|
|
console.log(`Finished ${bucketName}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log('Done!');
|
||
|
|
} finally {
|
||
|
|
await client.close();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
exportGridFS();
|