-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
49 lines (43 loc) · 1.38 KB
/
index.js
File metadata and controls
49 lines (43 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var fs = require('fs'),
request = require('request'),
Promise = require('bluebird'),
extension = require('./extension.json'),
_ = require('lodash');
function normalisePath(path){
if(_.endsWith(path,'/')){
path = path.slice(0,-1);
}
return path;
}
exports.saveFile = function(url,path,fileName){
path = normalisePath(path);
return new Promise(function(resolve,reject){
request.get({
"uri":url,
"encoding": null
},function(error,response,body){
var mimeType = response.headers['content-type'];
var ext = "";
_.forEach(extension,function(obj){
if(obj.mime === mimeType){
ext = obj.extension;
}
})
if (!fs.existsSync(path)){
fs.mkdirSync(path);
}
var data = new Buffer(body).toString('base64');
fs.writeFile(path + "/" + fileName +'.' + ext,data,'base64',function(err){
if(err){
reject(err);
}
var obj = {
"size":response.headers["content-length"],
"filename":fileName + '.' + ext,
"path":path + "/" + fileName +'.' + ext
}
resolve(obj);
})
})
})
}