1 | require('events').EventEmitter.defaultMaxListeners = 0;
|
2 | const Client = require('ssh2-sftp-client');
|
3 | const chalk = require('chalk');
|
4 | const utils = require('./utils');
|
5 |
|
6 | const {log} = utils;
|
7 |
|
8 | function sshUpload(sshOptions, assetsMap, folders = [], fn) {
|
9 | const sftp = new Client();
|
10 | let { username, password, target, host, port } = sshOptions;
|
11 | log.info(chalk.green('ready to connect to sftp.\n'));
|
12 | sftp.connect({
|
13 | host,
|
14 | port,
|
15 | username,
|
16 | password
|
17 | })
|
18 | .then(() => {
|
19 | log.info(chalk.green(`connected to ${username}@${host} successful !`));
|
20 |
|
21 | if(folders.length) {
|
22 | log.info(chalk.green('\ninit directories ...\n'));
|
23 | const folderPromises = folders.map(folder => {
|
24 | return new Promise((rs, rj) => {
|
25 | const rfolder = normalizePath(target + folder);
|
26 | sftp.mkdir(rfolder).then(_ => rs(), _ => rs());
|
27 | });
|
28 | });
|
29 | Promise.all(folderPromises).then(res => {
|
30 | let promises = assetsMap.map(item => {
|
31 | return new Promise(function(rs, rj) {
|
32 | sftp.put(item.assetSource, normalizePath(target + item.locPath), {encoding: 'utf8'})
|
33 | .then(function() {
|
34 | const uploaded = normalizePath(item.locPath);
|
35 | console.log('uploaded ', uploaded)
|
36 | rs(uploaded);
|
37 | })
|
38 | .catch(function(err) {
|
39 | rj(err);
|
40 | });
|
41 | });
|
42 | });
|
43 | return Promise.all(promises)
|
44 | .then(res => {
|
45 | log.info('uploaded all.');
|
46 | fn && fn();
|
47 | sftp.end();
|
48 | })
|
49 | .catch(_ => {
|
50 | log.info(_);
|
51 | sftp.end();
|
52 | });
|
53 | });
|
54 | }
|
55 | })
|
56 |
|
57 | }
|
58 |
|
59 | function normalizePath(source) {
|
60 | return source.replace(/\\/g, "/").replace(/\/+/g, "/");
|
61 | }
|
62 |
|
63 | module.exports = sshUpload;
|