采用 ftp 模块上传文件
const FtpClient
= require('ftp');
const fs
= require('fs');
const client
= new FtpClient();
const config
= {
host
: '127.0.0.1',
port
: 21,
keepalive
: 10000
}
function connect() {
return new Promise((resolve
, reject
) => {
client
.on('ready', () => {
console
.log('ftp ready');
resolve();
})
client
.on('close', () => {
console
.log('ftp close');
});
client
.on('end', () => {
console
.log('ftp end');
});
client
.on('error', (err
) => {
console
.log('ftp err', err
);
reject(err
)
});
client
.connect(config
);
})
}
async function upload(sourcePath
, targetPath
) {
if (!fs
.existsSync(sourcePath
)) {
return false;
}
await connect();
return new Promise((resolve
, reject
) => {
client
.put(sourcePath
, targetPath
, (err
) => {
client
.end();
if (err
) {
console
.log(err
);
reject(false);
} else {
console
.log(`upload file completed. filePath: ${targetPath}`);
resolve(true);
}
})
});
}
const fileName
= 'ftp-upload-file.txt';
const sourcePath
= `./${fileName}`;
const targetPath
= `upload/${fileName}`;
upload(sourcePath
, targetPath
);
转载请注明原文地址:https://tech.qufami.com/read-11342.html