-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
87 lines (80 loc) · 2.64 KB
/
index.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var Client = require('ftp');
var fs = require('fs');
var spinner = require('ora')()
var client = new Client();
module.exports = function({ host,user,password,sourceDir,targetDir }){
var filepaths = [];
function readFilesFromDir(parentPath,filePath){
let currentPath = "";
if(parentPath === ""){
currentPath = filePath;
}else{
currentPath = parentPath+'/'+filePath;
}
let sourcePath = `${sourceDir}/${currentPath}`;
if(fs.lstatSync(sourcePath).isDirectory()){
let files = fs.readdirSync(sourcePath);
for(let filePath of files){
readFilesFromDir(currentPath,filePath);
}
}else{
filepaths.push(currentPath)
}
}
function readyFn(){
spinner.start();
fs.readdir(sourceDir, function(err,files){
if(err) throw err;
for(let filePath of files){
readFilesFromDir("",filePath);
}
transferFiles();
})
}
function transferFile(filePath){
return new Promise((res,rej)=>{
let parentPath = filePath.lastIndexOf('/') !== -1 && filePath.substring(0 , filePath.lastIndexOf('/') );
let sourcePath = `${sourceDir}/${filePath}`;
let targetPath = `${targetDir}/${filePath}`;
let newDirInServer = `${targetDir}/${parentPath}`;
if(!parentPath || parentPath === '.'){
client.put(sourcePath, targetPath,function(err) {
if (err) throw err;
console.log(sourcePath+'-----'+targetPath)
res(true);
});
}else{
client.mkdir(newDirInServer,true,function(err){
if(err) throw err;
client.put(sourcePath, targetPath,function(err) {
if (err) throw err;
console.log(sourcePath+'-----'+targetPath)
res(true);
});
})
}
})
}
function transferFiles(){
let promises = [];
filepaths.forEach(filePath=>{
promises.push(transferFile(filePath))
})
Promise.all(promises).then(res=>{
console.log('上传成功!')
spinner.stop();
client.end();
}).catch(rej=>{
console.log('上传失败!');
spinner.stop();
client.end();
})
}
client.on('ready', readyFn);
// connect to localhost:21 as anonymous
client.connect({
host,
user,
password
});
}