• Stars
    star
    808
  • Rank 56,429 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 13 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Light and complete FTP client implementation for Node.js

jsftp

travis npm downloads styled with prettier

A client FTP library for NodeJS that focuses on correctness, clarity and conciseness. It doesn't get in the way and plays nice with streaming APIs.

Starting it up

const jsftp = require("jsftp");

const Ftp = new jsftp({
  host: "myserver.com",
  port: 3331, // defaults to 21
  user: "user", // defaults to "anonymous"
  pass: "1234" // defaults to "@anonymous"
});

jsftp gives you access to all the raw commands of the FTP protocol in form of methods in the Ftp object. It also provides several convenience methods for actions that require complex chains of commands (e.g. uploading and retrieving files, passive operations), as shown below.

When raw commands succeed they always pass the response of the server to the callback, in the form of an object that contains two properties: code, which is the response code of the FTP operation, and text, which is the complete text of the response.

Raw (or native) commands are accessible in the form Ftp.raw(command, params, callback)

Thus, a command like QUIT will be called like this:

Ftp.raw("quit", (err, data) => {
  if (err) {
    return console.error(err);
  }

  console.log("Bye!");
});

and a command like MKD (make directory), which accepts parameters, looks like this:

Ftp.raw("mkd", "/new_dir", (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log(data.text); // Show the FTP response text to the user
  console.log(data.code); // Show the FTP response code to the user
});

API and examples

new Ftp(options)

  • options is an object with the following properties:
{
  host: 'localhost', // Host name for the current FTP server.
  port: 3333, // Port number for the current FTP server (defaults to 21).
  user: 'user', // Username
  pass: 'pass', // Password
  createSocket: ({port, host}, firstAction) => {
    return net.createConnection({port, host}, firstAction);
  }, // function that creates the socket, default uses net.createConnection
}
  • options.createSocket could be used to implement a proxy for the ftp socket, e.g. socksv5
const {SocksClient} = require('socks');
const ftp = new Ffp({
  host: 'localhost',
  port: 3333,
  user: 'user',
  pass: 'password',
  createSocket: ({port, host}, firstAction) => {
    return SocksClient.createConnection({
      proxy: {
        ipaddress: '159.203.75.200'
        port: 1080,
        type: 5
      },

      command: 'connect',

      destination: {
        host,
        port
      }
    })
  }
})

Creates a new Ftp instance.

Ftp.host

Host name for the current FTP server.

Ftp.port

Port number for the current FTP server (defaults to 21).

Ftp.socket

NodeJS socket for the current FTP server.

Ftp.features

Array of feature names for the current FTP server. It is generated when the user authenticates with the auth method.

Ftp.system

Contains the system identification string for the remote FTP server.

Methods

Ftp.raw(command, [...args], callback)

With the raw method you can send any FTP command to the server. The method accepts a callback with the signature err, data, in which err is the error response coming from the server (usually a 4xx or 5xx error code) and the data is an object that contains two properties: code and text. code is an integer indicating the response code of the response and text is the response string itself.

Ftp.auth(username, password, callback)

Authenticates the user with the given username and password. If null or empty values are passed for those, auth will use anonymous credentials. callback will be called with the response text in case of successful login or with an error as a first parameter, in normal Node fashion.

Ftp.ls(filePath, callback)

Lists information about files or directories and yields an array of file objects with parsed file properties to the callback. You should use this function instead of stat or list in case you need to do something with the individual file properties.

ftp.ls(".", (err, res) => {
  res.forEach(file => console.log(file.name));
});

Ftp.list(filePath, callback)

Lists filePath contents using a passive connection. Calls callback with a string containing the directory contents in long list format.

ftp.list(remoteCWD, (err, res) => {
  console.log(res);
  // Prints something like
  // -rw-r--r--   1 sergi    staff           4 Jun 03 09:32 testfile1.txt
  // -rw-r--r--   1 sergi    staff           4 Jun 03 09:31 testfile2.txt
  // -rw-r--r--   1 sergi    staff           0 May 29 13:05 testfile3.txt
  // ...
});

Ftp.get(remotePath, callback)

Gives back a paused socket with the file contents ready to be streamed, or calls the callback with an error if not successful.

var str = ""; // Will store the contents of the file
ftp.get("remote/path/file.txt", (err, socket) => {
  if (err) {
    return;
  }

  socket.on("data", d => {
    str += d.toString();
  });

  socket.on("close", err => {
    if (hadErr) {
      console.error("There was an error retrieving the file.");
    }
  });

  socket.resume();
});

Ftp.get(remotePath, localPath, callback)

Stores the remote file directly in the given local path.

ftp.get("remote/file.txt", "local/file.txt", err => {
  if (hadErr) {
    return console.error("There was an error retrieving the file.");
  }
  console.log("File copied successfully!");
});

Ftp.put(source, remotePath, callback)

Uploads a file to filePath. It accepts a string with the local path for the file, a Buffer, or a Readable stream as a source parameter.

ftp.put(buffer, "path/to/remote/file.txt", err => {
  if (!err) {
    console.log("File transferred successfully!");
  }
});

Ftp.rename(from, to, callback)

Renames a file in the server. from and to are both filepaths.

ftp.rename(from, to, (err, res) => {
  if (!err) {
    console.log("Renaming successful!");
  }
});

Ftp.keepAlive([wait])

Refreshes the interval thats keep the server connection active. wait is an optional time period (in milliseconds) to wait between intervals.

You can find more usage examples in the unit tests. This documentation will grow as jsftp evolves.

Installation

npm install jsftp

Tests and Coverage

JSFtp tests against ProFTPD by default. To accomplish that, it uses a Docker set-up, so you'll need Docker installed in your machine in order to run tests.

Please note that the first time you run the tests it will take a while, given that it has to download, configure and run the containerized ProFTPD server.

To run tests and coverage reports:

npm test

...
43 passing (10s)

|-----------|----------|----------|----------|----------|----------------|
|File       |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
|-----------|----------|----------|----------|----------|----------------|
|All files  |    86.47 |    73.17 |    95.45 |    86.47 |                |
|jsftp      |      100 |      100 |      100 |      100 |                |
|  index.js |      100 |      100 |      100 |      100 |                |
|jsftp/lib  |    86.43 |    73.17 |    95.45 |    86.43 |                |
|  jsftp.js |    86.43 |    73.17 |    95.45 |    86.43 |... 722,724,733 |
|-----------|----------|----------|----------|----------|----------------|

License

See LICENSE.

More Repositories

1

go-diff

Diff, match and patch text in Go
Go
1,827
star
2

virtual-list

Scrollable list of DOM elements that can hold an unlimited amount of rows without breaking a sweat
JavaScript
265
star
3

jsmidi

Library for reading/writing midi files in JavaScript
JavaScript
185
star
4

narwhal-mongodb

Wrapper of MongoDB database for CommonJS
JavaScript
94
star
5

tabgrenade

Tab Grenade is a Firefox Browser extension that creates a persistent list of all your open tabs and then closes them all.
JavaScript
62
star
6

abcnode

Node.js parser for the ABC music notation format
JavaScript
27
star
7

Design-By-Canvas

Port of John Maeda's Design By Numbers to Javascript using PEG.js
JavaScript
20
star
8

parse-listing

Small library to parse file listings into JavaScript objects
JavaScript
16
star
9

xslty

Command-line XSLT 2.0 processor
JavaScript
13
star
10

re-alpine

Mirror of the official re-alpine repository at sourceforge.net
C
12
star
11

rxjs-minimal-boilerplate

Minimal boilerplate for a barebones project in modern RxJS
JavaScript
11
star
12

par

par is a paragraph reformatter, vaguely similar to fmt, but better.
C
10
star
13

pipeline2dcd

Converts JSON Spinnaker pipelines to DCD pipelines (https://github.com/spinnaker/dcd-spec)
JavaScript
9
star
14

siphon

Stream commands output to your browser
Go
8
star
15

cascade

A desktop IRC client made using Node and AngularJS
JavaScript
7
star
16

ftp-test-server

Simple wrapper around pyftpdlib to have an easy FTP server to try stuff with
Python
6
star
17

mlkit

Mirror of the official smltojs SVN repository
Standard ML
4
star
18

ftp-response-parser

Streaming parser for FTP responses
JavaScript
3
star
19

Wakame

Wakame is a Gtk application that acts as a frontend to Wesabe and adds some extra functionality such as complex filters, graphs and persistence.
C#
3
star
20

enumjs

Enumeration over abstract collection of elements, in a functional way.
JavaScript
2
star
21

vimfiles

My vim config
Vim Script
2
star
22

jsmacros

Sweet.js macro collection for JavaScript
JavaScript
2
star
23

sergimansilla.com

My personal website
2
star
24

gab

JavaScript
2
star
25

sergi-vim

My vim environment
Vim Script
2
star
26

coconut

An idempotent photo organizer
Go
2
star
27

detect-failed-junit

Returns error if there are any test suites that failed or errored in a JUnit test report
Go
2
star
28

solitaire

Bruce Schneier's Solitaire cryptoalgorithm implemented in a variety of languages
2
star
29

conceal

Conceals a string or part of it.
JavaScript
2
star
30

rxjs-codemod

JavaScript
2
star
31

sergi.github.com

Personal blog
CSS
1
star
32

parcel_testcase

JavaScript
1
star
33

evidence

C#
1
star
34

mime-multipart

Library to help creating Mime Multi Part Archives
JavaScript
1
star
35

Tagger

Tagger is a speed tagging extension for Thunderbird
JavaScript
1
star
36

vim-chicken-doc

Vim plugin that integrates chicken-doc for scheme files
Vim Script
1
star
37

mesos-scheduler

Simple Scheduler from scratch for Apache Mesos
JavaScript
1
star
38

roughdb-clj

Clojure
1
star
39

XPMParser.js

A parser of the XPM graphical format implemented in JavaScript
JavaScript
1
star
40

geekdots

JavaScript
1
star
41

siphon-ui

UI for Siphon
CSS
1
star
42

roughdb

JavaScript
1
star
43

FoxStat

F#
1
star
44

jpl-website

JavaScript
1
star
45

nodejsconfit2012

Code for the talk given at http://nodejsconf.it/ 2012
JavaScript
1
star