Node.js 中使用 ssh2-sftp-client 上传文件到服务器示例
配置文件 sftp.json
{
"zhixingyun_production": {
"sftp": {
"host": "10.10.10.10",
"port": 22,
"username": "xxx",
"password": "xxx"
},
"pathConfig": {
"remotePath": "/home/xiaochong/web/website/dist",
"remoteBackupPath": "/home/xiaochong/web/website/dist_backup",
"localPath": "./dist"
}
},
"zhixingyun_test": {
"sftp": {
"host": "10.10.10.10",
"port": 22,
"username": "xxx",
"password": "xxx"
},
"pathConfig": {
"remotePath": "/home/xiaochong/web/test",
"remoteBackupPath": "/home/xiaochong/web/test_backup",
"localPath": "./test"
}
}
}
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
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
上传文件 upload.js
let Client = require('ssh2-sftp-client');
let client = new Client();
const config = require('./sftp.json')
const args = process.argv.slice(2)
const { sftp, pathConfig } = config[args[0]];
const main = async () => {
try {
await client.connect(sftp);
//删除备份文件,如果有
if (await client.exists(pathConfig.remoteBackupPath)) {
await client.rmdir(pathConfig.remoteBackupPath, true)
console.log('删除备份文件成功')
}
// 重命名之前的文件作为备份文件
if (await client.exists(pathConfig.remotePath)) {
await client.rename(pathConfig.remotePath, pathConfig.remoteBackupPath)
console.log('新的备份文件重命名成功');
}
// 上传本地文件
await client.uploadDir(pathConfig.localPath, pathConfig.remotePath);
console.log('上传成功')
} catch (err) {
console.log(err);
} finally {
client.end();
}
}
main();
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
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
最后我们怎么执行upload呢,打包后用node执行即可:
`package.json`
```json
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build & node script/upload.js zhixingyun_production",
"build:test": "vue-cli-service build --mode test & node script/upload.js zhixingyun_test",
}
1
2
3
4
5
6
7
2
3
4
5
6
7
注意点:sftp
里的localPath
写的是./
因为npm run build
执行时,dist
文件夹在当前命令行的同级目录。
这种上传方式是 SFTP,不是stp,用的账号密码是ssh的。
上次更新: 2024/04/07, 16:22:38
- 01
- linux 在没有 sudo 权限下安装 Ollama 框架12-23
- 02
- Express 与 vue3 使用 sse 实现消息推送(长连接)12-20