【发布时间】:2021-06-02 15:14:02
【问题描述】:
因为有些东西叫做“回调地狱”。这是我可以从服务器获取文件到我的 vps 电脑并上传的唯一方法。过程很简单:
- 从 ftp 服务器下载 .json 文件
- 在电脑上编辑.json文件
- 上传.json文件并删除电脑的副本。
但是我的问题是:虽然它下载一次,但它会根据我在 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
【问题讨论】:
-
为什么您的代码结构为单行但实际缩进?不要滥用参数、逗号运算符和三元组来进行变量赋值和流控制。
-
参数与 'let' 没有什么不同,因为它是基于范围的。
-
参数的预期用途是什么?不是“声明局部变量”,我很确定
-
其实上面列出的参数都是当作变量来对待的。如果是你不喜欢的东西,我可以理解。正如我已故的导师所说,“用花岗岩雕刻大象的方法不止一种”。问题是为什么每次连续之后都有重复的 put 命令。
标签: javascript node.js functional-programming functional-testing node-ftp