javascript/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path')
const { NodeSSH } = require('node-ssh')
const home = require("home");
const subProjectRoot = path.join('/www/wwwroot/www.example.com', 'subProjectPath').replace(/\\/g, '/')
/* eslint-enable @typescript-eslint/no-var-requires */
const ssh = new NodeSSH()
const join = (relativePath) => path.join(__dirname, '..', relativePath)
const putDirectory = async (fromDirectory, toDirectory) => {
// Putting entire directories
// const failed = []
// const successful = []
await ssh
.putDirectory(fromDirectory, toDirectory, {
recursive: true,
concurrency: 10,
// ^ WARNING: Not all servers support high concurrency
// try a bunch of values and see what works on your server
validate(itemPath) {
const baseName = path.basename(itemPath)
return (
baseName.substr(0, 1) !== '.' // do not allow dot files
&& baseName !== 'node_modules'
) // do not allow node_modules
},
tick(localPath, remotePath, error) {
if (error) {
// failed.push(localPath)
} else {
// successful.push(localPath)
}
},
})
.then((status) => {
// eslint-disable-next-line no-console
console.log(`transfer was ${
status ? 'successful' : 'unsuccessful'
}: [${fromDirectory} => ${toDirectory}]`)
// console.log('failed transfers', failed.join(', '))
// console.log('successful transfers', successful.join(', '))
})
}
async function restart() {
await ssh.connect({
host: "123.456.78.90",
port: 22,
username: "username",
// 私钥路径(不使用私钥的话,把下面这行换成`password`字段,填SSH登录密码)
privateKeyPath: path.join(home.resolve("~"), ".ssh/id_rsa"),
});
await putDirectory(join('/dist'), subProjectRoot)
const singleFileList = [
'/README.md',
].map((fileName) => ({
local: join(fileName),
remote: `${subProjectRoot}${fileName}`,
}))
await ssh.putFiles(singleFileList).then(
() => {
// eslint-disable-next-line no-console
console.log('The File thing is done')
},
(error) => {
// eslint-disable-next-line no-console
console.log("Something's wrong")
// eslint-disable-next-line no-console
console.log(error)
},
)
const execCommand = 'pwd'
await ssh.execCommand(execCommand, {
cwd: subProjectRoot,
onStdout(chunk) {
// eslint-disable-next-line no-console
console.log('onStdout')
// eslint-disable-next-line no-console
console.log(chunk.toString('utf8'))
},
onStderr(chunk) {
// eslint-disable-next-line no-console
console.log('onStderr')
// eslint-disable-next-line no-console
console.log(chunk.toString('utf8'))
throw new Error('failed')
},
})
// eslint-disable-next-line no-console
console.log('发布结束')
process.exit(0)
}
restart().catch((err) => {
setTimeout(() => {
throw err
}, 0)
})
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104