UNPKG

3.07 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.ftp = void 0;
7const basic_ftp_1 = require("basic-ftp");
8const stream_1 = require("stream");
9const path_1 = require("path");
10const debug_1 = __importDefault(require("debug"));
11const notfound_1 = __importDefault(require("./notfound"));
12const notmodified_1 = __importDefault(require("./notmodified"));
13const debug = (0, debug_1.default)('get-uri:ftp');
14/**
15 * Returns a Readable stream from an "ftp:" URI.
16 */
17const ftp = async (url, opts = {}) => {
18 const { cache } = opts;
19 const filepath = decodeURIComponent(url.pathname);
20 let lastModified;
21 if (!filepath) {
22 throw new TypeError('No "pathname"!');
23 }
24 const client = new basic_ftp_1.Client();
25 try {
26 const host = url.hostname || url.host || 'localhost';
27 const port = parseInt(url.port || '0', 10) || 21;
28 const user = url.username || undefined;
29 const password = url.password || undefined;
30 await client.access({
31 host,
32 port,
33 user,
34 password,
35 ...opts,
36 });
37 // first we have to figure out the Last Modified date.
38 // try the MDTM command first, which is an optional extension command.
39 try {
40 lastModified = await client.lastMod(filepath);
41 }
42 catch (err) {
43 // handle the "file not found" error code
44 if (err.code === 550) {
45 throw new notfound_1.default();
46 }
47 }
48 if (!lastModified) {
49 // Try to get the last modified date via the LIST command (uses
50 // more bandwidth, but is more compatible with older FTP servers
51 const list = await client.list((0, path_1.dirname)(filepath));
52 // attempt to find the "entry" with a matching "name"
53 const name = (0, path_1.basename)(filepath);
54 const entry = list.find((e) => e.name === name);
55 if (entry) {
56 lastModified = entry.modifiedAt;
57 }
58 }
59 if (lastModified) {
60 if (isNotModified()) {
61 throw new notmodified_1.default();
62 }
63 }
64 else {
65 throw new notfound_1.default();
66 }
67 const stream = new stream_1.PassThrough();
68 const rs = stream;
69 client.downloadTo(stream, filepath).then((result) => {
70 debug(result.message);
71 client.close();
72 });
73 rs.lastModified = lastModified;
74 return rs;
75 }
76 catch (err) {
77 client.close();
78 throw err;
79 }
80 // called when `lastModified` is set, and a "cache" stream was provided
81 function isNotModified() {
82 if (cache?.lastModified && lastModified) {
83 return +cache.lastModified === +lastModified;
84 }
85 return false;
86 }
87};
88exports.ftp = ftp;
89//# sourceMappingURL=ftp.js.map
\No newline at end of file