问题描述
因为有些东西叫做“回调地狱”。这是我可以将文件从服务器获取到我的 vps 电脑并上传的唯一方法。过程很简单:
但是我的问题是这样的:虽然它下载了一次,但它会根据我在 1 个会话期间命令它的次数返回上传(命令 #1,执行一次,命令 #2,执行两次等)。
我试图以命令方式运行它,但被取消了。不得不求助于回调地狱来几乎正确地运行代码。触发器用于初始化命令,但命令和会话无效。
(( //declaring my variables as parameters
ftp=new (require('ftp'))(),fs=require('fs'),serverFolder='./Path/Of/Server/',localFolder='./Path/Of/Local/',file='some.json',{log}=console
)=>{
//run server if its ready
ftp.on('ready',()=>{
//collect a list of files from the server folder
ftp.list(serverFolder+file,(errList,list)=>
errList|| typeof list === 'object' &&
list.forEach($file=>
//if the individual file matches,resume to download the file
$file.name===file&&(
ftp.get(serverFolder+file,(errGet,stream)=>
errGet||(
log('files matched! cdarry onto the operation...'),stream.pipe(fs.createReadStream(localFolder+file)),stream.once('close',()=>{
//check if the file has a proper size
fs.stat(localFolder+file,(errStat,stat)=>
errStat || stat.size === 0
//will destroy server connection if bytes = 0
?(ftp.destroy(),log('the file has no value'))
//uploads if the file has a size,edits,and ships
:(editThisFile(),ftp.put(
fs.createReadStream(localFolder+file),serverFolder+file,err=>err||(
ftp.end(),log('process is complete!')
))
//editThisFile() is a place-holder editor
//edits by path,and object
)
})
)
)
)
)
);
});
ftp.connect({
host:'localHost',password:'1Forrest1!',port:'21',keepalive:0,debug: console.log.bind(console)
});
})()
主要问题是:由于某种原因,它会一遍又一遍地返回命令的副本作为“结转”。
编辑:虽然“编程风格”的优点与普通元不同。这一切都会导致回调地狱的相同问题。需要任何建议。 为了可读性,我帮助编辑了我的代码以减轻困难。 Better Readability version
解决方法
ftp
模块 API 导致回调地狱。它也有一段时间没有维护并且是错误的。尝试使用像 basic-ftp
这样的 Promise 的模块。
有了 promises,代码流变得更容易推理,错误不需要特殊处理,除非你愿意。
const ftp = require('basic-ftp')
const fsp = require('fs').promises
async function updateFile(localFile,serverFile){
const client = new ftp.Client()
await client.access({
host: 'localHost',password: '1Forrest1!',})
await client.downloadTo(localFile,serverFile)
const stat = await fsp.stat(localFile)
if (stat.size === 0) throw new Error('File has no size')
await editThisFile(localFile)
await client.uploadFrom(localFile,serverFile)
}
const serverFolder = './Path/Of/Server'
const localFolder = './Path/Of/Local'
const file = 'some.json'
updateFile(localFolder + file,serverFolder + file).catch(console.error)