如何同个js去管理FTP或者js文件去上传文件
时间: 2023-10-22 19:05:04 浏览: 36
你可以使用Node.js中的内置模块`ftp`来管理FTP,或者使用第三方模块`ssh2-sftp-client`来上传文件。
以下是一个使用`ftp`模块连接FTP服务器并上传文件的示例代码:
```javascript
const ftp = require('ftp');
const fs = require('fs');
const client = new ftp();
const file = 'example.txt';
const remotePath = '/example.txt';
client.on('ready', () => {
client.put(fs.createReadStream(file), remotePath, (err) => {
if (err) throw err;
console.log('File uploaded successfully.');
client.end();
});
});
client.connect({
host: 'ftp.example.com',
user: 'username',
password: 'password'
});
```
以下是一个使用`ssh2-sftp-client`模块连接SFTP服务器并上传文件的示例代码:
```javascript
const SftpClient = require('ssh2-sftp-client');
const fs = require('fs');
const sftp = new SftpClient();
sftp.connect({
host: 'sftp.example.com',
port: 22,
username: 'username',
password: 'password'
})
.then(() => {
const file = 'example.txt';
const remotePath = '/example.txt';
return sftp.put(fs.createReadStream(file), remotePath);
})
.then(() => {
console.log('File uploaded successfully.');
sftp.end();
})
.catch((err) => {
console.error(err.message);
sftp.end();
});
```
以上示例代码仅供参考,具体实现应根据实际需求进行调整。