如何在NodeJS中通过FTP下载文件? [英] How to download file over FTP in NodeJS?
问题描述
我想使用绝对FTP URL下载文件,例如 ftp://host:port/dir/file.extension
I want to download file using absolute FTP URL, like ftp://host:port/dir/file.extension
我尝试了 node-libcurl,wget,wget改进的请求
.所有人都失败了,说协议必须是HTTP或HTTPS.
I've tried node-libcurl, wget, wget-improved, request
. All failed saying that the protocol must be either HTTP or HTTPS.
有一些可用于Node的FTP客户端(在npmjs上可用).但是,根据他们的文档,他们需要创建与FTP服务器的连接,更改目录然后下载.
There are FTP clients available for Node (available on npmjs). But, as per their documentation, they require creating a connection to FTP Server, change directory and then download it.
有什么简单的解决方法吗?
Is there any simple solution?
推荐答案
在这里,我将概述一种简单的方法(并且没有完整的代码解决方案!). FTP 基于
I will outline a simple approach here (and no complete solution with code!). FTP is based upon TCP with a simple human readable protocol. In order to fetch a file from an FTP server you need to do the following:
- 使用
net.Socket
< - 使用
socket.connect
在端口21上连接到FTP服务器 - 使用
socket.write
与服务器进行通信发送数据和socket.on('data')
到读取数据
- Create a TCP socket using
net.Socket
- Use
socket.connect
to connect to your FTP server on port 21 - Communicate with the server using
socket.write
to send data andsocket.on('data')
to read data
此博客帖子,可以总结如下:
- 使用
net.Socket.connect
连接到服务器 - 使用
USER
命令设置用户 - 通过
PASS
进行身份验证 - 使用
CWD
转到所需目录 - 使用
PASV
更改为被动模式 - 阅读服务器回复以找出要连接的IP和端口以获取文件
- 在上一步的IP和端口上打开另一个套接字
- Voilà!
这篇关于如何在NodeJS中通过FTP下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!