const https = require('https'); const fs = require('fs-extra'); const path = require('path'); module.exports = Self => { Self.remoteMethod('download', { description: 'Returns last entries', accessType: 'WRITE', returns: { type: ['Object'], root: true }, http: { path: `/download`, verb: 'GET' } }); Self.download = async() => { const models = Self.app.models; let filePath; try { const imageQueue = await Self.find({ where: { itemFk: 410421 } }); // const rootPath = 'C:\\Users\\jsanc\\Desktop\\images'; const rootPath = '/var/lib/salix/image'; const tempPath = path.join(rootPath, 'temp'); // Create temporary path await fs.mkdir(tempPath); for (let image of imageQueue) { const fileName = `${image.itemFk}.png`; filePath = path.join(tempPath, fileName); https.get(image.url, async response => { // Upload file to temporary path const file = fs.createWriteStream(filePath); response.pipe(file); await models.Image.register('catalog', fileName, filePath); // await image.destroy(); }); } return imageQueue; } catch (e) { fs.unlink(filePath); throw e; } }; };