Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extending contentCreate() to fetch files from remote URL #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions lib/res/contents.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ const fs = require('fs');
const fsp = require('when/node').liftAll(fs);
const path = require('path');
const validator = require('../validator');
var request = require('request');

/**
/*
* @description File Object
*
* @namespace File
Expand All @@ -16,6 +17,7 @@ const validator = require('../validator');
* @property {String} base64 - File contents as base64 encoded string
*/


const Contents = (Spark) => {
const contents = {
/**
Expand Down Expand Up @@ -71,7 +73,31 @@ const Contents = (Spark) => {
contentCreate: (filePath, timeout) => {
const t = (timeout && typeof _timeout === 'number') ? timeout : 15000;

if (validator.isFilePath(filePath)) {
var isurl=(filePath.slice(0,4)==="http"); // Fetching file from remote URL
if(isurl) {
var funcc = new Promise(function(resolve, reject){
console.log('Downloading via remote URL.');
var url=filePath;
request({ url, encoding: null }, (err, resp, buffer) => {
console.log("Buffer resolving.");
resolve(buffer);
console.log("Buffer resolved.");
});
});

return funcc
.then((bin) => {
const file = {};
file.name = path.basename(filePath);
file.ext = file.name.split('.').pop();
file.type = mime.lookup(file.ext);
file.binary = bin;
file.base64 = bin.toString('base64');
return when(file);
});
}

if (validator.isFilePath(filePath) && !isurl) { . // Fetching file from local URL
return fsp.readFile(filePath).timeout(t)
.then((bin) => {
const file = {};
Expand Down