SHARE
TWEET

Untitled

a guest Jun 16th, 2019 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2. const mkdirp = require('mkdirp');
  3. const path = require('path');
  4. const request = require('request');
  5. const url = require('url');
  6.  
  7. const downloadFile = async (file, targetFolder) => {
  8.   // Parse remote file spec
  9.   const sourceUrl = url.parse(file.url ? file.url.id : file.id);
  10.   const sourceHref = sourceUrl.href;
  11.   const sourcePath = path.parse(sourceUrl.path);
  12.   const sourceBase = sourcePath.base;
  13.  
  14.   // Ensure folder exists
  15.   mkdirp.sync(targetFolder);
  16.  
  17.   // Generate local file path/name
  18.   const localFile = path.resolve(targetFolder, sourceBase);
  19.  
  20.   // Download
  21.   return new Promise((resolve, reject) => {
  22.     request(sourceHref)
  23.       .pipe(fs.createWriteStream(localFile))
  24.       .on('error', error => reject(error))
  25.       .on('close', () => resolve(localFile));
  26.   });
  27. };
  28.  
  29. const uploadFile = async (localFile, remoteFolder) => {
  30.   return new Promise((resolve, reject) => {
  31.     const req = request.post(remoteFolder, function(err, resp, body) {
  32.       if (err) {
  33.         reject(err);
  34.       } else {
  35.         if (resp.statusCode !== 200) {
  36.           // console.log('resp:', resp)
  37.           reject(
  38.             new Error(
  39.               `Failed to upload: ${resp.statusCode} - ${resp.statusMessage}`
  40.             )
  41.           );
  42.         }
  43.         const url = body.slice('File uploaded: '.length);
  44.         resolve(url);
  45.       }
  46.     });
  47.     const form = req.form();
  48.     form.append('file', fs.createReadStream(localFile));
  49.   });
  50. };
  51.  
  52. module.exports = {
  53.   downloadFile,
  54.   uploadFile
  55. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top