ChatGPT 的回答一般挺不错的,比搜索引擎好很多。经常问它一些问题,大部分时候有满意的答案。当然不是 100% 满意,有时答案是错的,甚至明显是错的,然后我就会忽略错误答案,或者它的回答不完全对,但我也能补充出正确答案,然后就结束对话了。但今天我尝试指出它的错误,它竟然修复了。
起因:
我想写一段 JavaScript 使用 sftp 传文件夹的代码,
首先安装依赖
npm install ssh2-sftp-client
ChatGPT 给的答案是:
const Client = require('ssh2-sftp-client');
const path = require('path');
const fs = require('fs');
const sftp = new Client();
const config = {
host: 'your.server.com',
port: 22,
username: 'your-username',
password: 'your-password', // Alternatively, use SSH keys
// privateKey: require('fs').readFileSync('/path/to/your/private-key')
};
const localDir = '/path/to/local/folder'; // Local directory to upload
const remoteDir = '/path/to/remote/folder'; // Remote destination directory
// Function to recursively upload files and directories
async function uploadDir(localPath, remotePath) {
try {
// Connect to the SFTP server
await sftp.connect(config);
// Ensure the remote directory exists
await sftp.mkdir(remotePath, true); // 'true' means recursive mkdir
// Read the contents of the local directory
const files = await fs.promises.readdir(localPath);
// Iterate through each file/subdirectory in the local directory
for (let file of files) {
const localFile = path.join(localPath, file);
const remoteFile = path.join(remotePath, file);
// Check if it's a file or directory
const stats = await fs.promises.stat(localFile);
if (stats.isDirectory()) {
// If it's a directory, recursively upload it
await uploadDir(localFile, remoteFile);
} else {
// If it's a file, upload it
await sftp.put(localFile, remoteFile);
console.log(`Uploaded file: ${localFile} -> ${remoteFile}`);
}
}
console.log('Directory upload complete!');
} catch (err) {
console.error('Error uploading directory:', err);
} finally {
// Close the SFTP connection
sftp.end();
}
}
// Start uploading the directory
uploadDir(localDir, remoteDir);
这里有个问题,文件夹可能会有子文件夹,会递归调用 uploadDir 方法,在递归调用时会重复连接 sftp ,会报错:
Error: connect: An existing SFTP connection is already defined
at SftpClient.fmtError (/Users/wjf/wjf/repo/js-scp/node_modules/ssh2-sftp-client/src/index.js:94:22)
at SftpClient.connect (/Users/wjf/wjf/repo/js-scp/node_modules/ssh2-sftp-client/src/index.js:188:20)
at uploadDir (/Users/wjf/wjf/repo/js-scp/test2.js:32:20)
at uploadDir (/Users/wjf/wjf/repo/js-scp/test2.js:50:23) {
code: 'ERR_NOT_CONNECTED',
custom: true
}
于是向 ChatGPT 指出错误:This code do not work. Because in the recursion, you connect sftp multiple times
于是 ChatGPT 重新写了代码,把连接 sftp 放在递归函数的外面,给出了可运行的代码。
const Client = require('ssh2-sftp-client');
const path = require('path');
const fs = require('fs');
const sftp = new Client();
const config = {
host: 'your.server.com',
port: 22,
username: 'your-username',
password: 'your-password', // Alternatively, use SSH keys
// privateKey: require('fs').readFileSync('/path/to/your/private-key')
};
const localDir = '/path/to/local/folder'; // Local directory to upload
const remoteDir = '/path/to/remote/folder'; // Remote destination directory
// Function to recursively upload files and directories
async function uploadDir(localPath, remotePath) {
try {
// Read the contents of the local directory
const files = await fs.promises.readdir(localPath);
// Iterate through each file/subdirectory in the local directory
for (let file of files) {
const localFile = path.join(localPath, file);
const remoteFile = path.join(remotePath, file);
// Check if it's a file or directory
const stats = await fs.promises.stat(localFile);
if (stats.isDirectory()) {
// If it's a directory, create it on the remote server
await sftp.mkdir(remoteFile, true); // 'true' means recursive mkdir
console.log(`Created directory: ${remoteFile}`);
// Recursively upload the directory's contents
await uploadDir(localFile, remoteFile);
} else {
// If it's a file, upload it
await sftp.put(localFile, remoteFile);
console.log(`Uploaded file: ${localFile} -> ${remoteFile}`);
}
}
console.log('Directory upload complete!');
} catch (err) {
console.error('Error uploading directory:', err);
}
}
// Start the upload process
async function startUpload() {
try {
// Connect to the SFTP server once
await sftp.connect(config);
// Upload the entire directory
await uploadDir(localDir, remoteDir);
} catch (err) {
console.error('Error during connection or upload:', err);
} finally {
// Always end the SFTP connection when done
sftp.end();
}
}
// Start the process
startUpload();
没想到人工智能还可以这样操作!
评论