프로젝트를 진행하면서 ftp 를 사용해서 외부 디렉토리의 파일을 다운로드 받아야하는 상황이 생겼다.
node 에는 ftp module 이 있으므로 쉽게 연결할 수 있다.
import Client from "ftp";
import fs from "fs";
const c = new Client();
c.connect({
host: "xxx.xxx.xxx.xxx",
user: "xxxxx",
password: "xxxxx",
port: "xxxx",
});
c.on("ready", () => {
c.get("hello.txt", (err, stream) => {
stream.once("close", () => { c.end(); });
stream.pipe(fs.createWriteStream("hi.txt"));
});
});
기본적인 사용법은 이렇게
c.connect 를 통해 ip, port 등 기본적인 연결정보를 입력하고
c.on() 을 통해 "ready" 이벤트로 연결이 완료된 후에 작업을 진행할 수 있다.
c.end() 는 연결을 종료하는 기능이다. 하지만 c.destroy() 와는 다른 성격을 띄는데,
상기의 REFS 링크를 참고하면
end() 의 경우 실행된 명령이 끝난 후에 연결을 끊고
destroy() 는 즉시 연결을 끊는다는 차이가 있다.
그래서 파일을 저장이 끝난뒤에 연결을 끊으려면 Promise 를 같이 응용하면 된다.
import Client from "ftp";
import fs from "fs";
const c = new Client();
c.connect({
host: "xxx.xxx.xxx.xxx",
user: "xxxxx",
password: "xxxxx",
port: "xxxx",
});
c.on("ready", () => {
c.get("hello.txt", async(err, stream) => {
const writeStream = fs.createWriteStream("hi.txt");
const promiseExecute = async() => {
return new Promise((resolve) => {
stream.pipe(writeStream);
writeStream.on("finish", () => {
c.end();
resolve();
});
});
}
await promiseExecute();
});
});
상기와 같이 c.get() 을 통해 가져온 file 의 stream 을 fs 모듈을 사용해 저장할 때
Promise 를 사용하여 파일이 모두 쓰여지면(writeStream.on("finish")) c.end() 통해
연결을 종료하도록 한다.