What is ftp?
The ftp npm package is a client for the File Transfer Protocol (FTP), which allows for the transfer of files between a client and a server on a computer network. It provides methods to read and write files, navigate the directory structure, and manage files and directories on the server.
What are ftp's main functionalities?
Connecting to an FTP server
This code sample demonstrates how to establish a connection to an FTP server using the ftp package. You need to provide the host, user, and password to connect.
const FTP = require('ftp');
const client = new FTP();
client.connect({ host: 'ftp.example.com', user: 'username', password: 'password' });
Listing files in a directory
This code sample shows how to list all files in a specific directory on the FTP server.
client.list('/path/to/directory', (err, list) => {
if (err) throw err;
console.dir(list);
});
Downloading a file
This code sample illustrates how to download a file from the FTP server. It saves the file to a local path.
client.get('remote/file/path.txt', (err, stream) => {
if (err) throw err;
stream.once('close', () => { client.end(); });
stream.pipe(fs.createWriteStream('local/file/path.txt'));
});
Uploading a file
This code sample demonstrates how to upload a file to the FTP server from a local path.
client.put('local/file/path.txt', 'remote/file/path.txt', (err) => {
if (err) throw err;
client.end();
});
Deleting a file
This code sample shows how to delete a file from the FTP server.
client.delete('remote/file/path.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully');
});
Other packages similar to ftp
basic-ftp
The basic-ftp package is an alternative to ftp that provides an easy-to-use API for interacting with an FTP server, including support for modern JavaScript features like async/await. It is designed to be both powerful and beginner-friendly.
jsftp
jsftp is a simple and lightweight FTP client for Node.js, with an emphasis on simplicity and ease of use. It offers a similar set of features to the ftp package but with a different API design.
promise-ftp
promise-ftp is an FTP client that wraps the ftp package's functionality in Promises, making it more suitable for use in modern asynchronous JavaScript code that utilizes async/await syntax.
ftp-srv
ftp-srv is a module for creating an FTP server rather than a client. It is useful for when you want to set up your own FTP server programmatically in Node.js, as opposed to connecting to an existing one.
Description
node-ftp is an FTP client module for node.js that provides an asynchronous interface for communicating with an FTP server.
Requirements
Install
npm install ftp
Examples
- Get a pretty-printed directory listing of the current (remote) working directory:
var FTPClient = require('ftp');
var conn = new FTPClient();
conn.on('connect', function() {
conn.auth(function(e) {
if (e)
throw e;
conn.list(function(e, entries) {
if (e)
throw e;
console.log('<start of directory list>');
for (var i=0,len=entries.length; i<len; ++i) {
if (typeof entries[i] === 'string')
console.log('<raw entry>: ' + entries[i]);
else {
if (entries[i].type === 'l')
entries[i].type = 'LINK';
else if (entries[i].type === '-')
entries[i].type = 'FILE';
else if (entries[i].type === 'd')
entries[i].type = 'DIR';
console.log(' ' + entries[i].type + ' ' + entries[i].size
+ ' ' + entries[i].date + ' ' + entries[i].name);
}
}
console.log('<end of directory list>');
conn.end();
});
});
});
conn.connect();
- Download remote file 'foo.txt' and save it to the local file system:
var fs = require('fs');
conn.get('foo.txt', function(e, stream) {
if (e)
throw e;
stream.on('success', function() {
conn.end();
});
stream.on('error', function(e) {
console.log('ERROR during get(): ' + e);
conn.end();
});
stream.pipe(fs.createWriteStream('localfoo.txt'));
});
- Upload local file 'foo.txt' to the server:
var fs = require('fs');
conn.put(fs.createReadStream('foo.txt'), 'remotefoo.txt', function(e) {
if (e)
throw e;
conn.end();
});
API
Events
-
connect() - Fires when a connection to the server has been successfully established.
-
timeout() - Fires if the connection timed out while attempting to connect to the server.
-
close(<boolean>hasError) - Fires when the connection is completely closed (similar to net.Socket's close event). The specified boolean indicates whether the connection was terminated due to a transmission error or not.
-
end() - Fires when the connection has ended.
-
error(<Error>err) - Fires when an exception/error occurs (similar to net.Socket's error event). The given Error object represents the error raised.
Methods
* Note 1: If a particular action results in an FTP-specific error, the error object supplied to the callback or 'error' event will contain 'code' and 'text' properties that contain the relevant FTP response code and the associated error text respectively.
* Note 2: Methods that return a boolean success value will immediately return false if the action couldn't be carried out for reasons including: no server connection or the relevant command is not available on that particular server.
Standard
These are actions defined by the "original" FTP RFC (959) and are generally supported by all FTP servers.
-
(constructor)([<object>config]) - Creates and returns a new instance of the FTP module using the specified configuration object. Valid properties of the passed in object are:
- <string>host - The hostname or IP address of the FTP server. Default: "localhost"
- <integer>port - The port of the FTP server. Default: 21
- <integer>connTimeout - The number of milliseconds to wait for a connection to be established. Default: 15000
- <function>debug - Accepts a string and gets called for debug messages Default: (no debug output)
-
connect(<integer>port,][<string>host]) - (void) - Attempts to connect to the FTP server. If the port and host are specified here, they override and overwrite those set in the constructor.
-
end() - (void) - Closes the connection to the server.
-
auth([<string>username, <string>password,] <function>callback) - <boolean>success - Authenticates with the server (leave out username and password to log in as anonymous). The callback has these parameters: the error (undefined if none).
-
list([<string>path,] [<boolean>streamList,] <function>callback) - <boolean>success_ - Retrieves the directory listing of the specified path. path defaults to the current working directory. If streamList is set to true, an EventEmitter will be passed to the callback, otherwise an array of objects (format shown below) and raw strings will be passed in to the callback. The callback has these parameters: the error (undefined if none) and a list source. If streaming the list, the following events are emitted on the list source:
-
entry(<object>entryInfo) - Emitted for each file or subdirectory. entryInfo contains the following possible properties:
- <string>name - The name of the entry.
- <string>type - A single character denoting the entry type: 'd' for directory, '-' for file, or 'l' for symlink (UNIX only).
- <string>size - The size of the entry in bytes.
- <Date>date - The last modified date of the entry.
- <object>rights - *(NIX only) - The various permissions for this entry.
- <string>user - An empty string or any combination of 'r', 'w', 'x'.
- <string>group - An empty string or any combination of 'r', 'w', 'x'.
- <string>other - An empty string or any combination of 'r', 'w', 'x'.
- <string>owner - *(NIX only) - The user name or ID that this entry belongs to.
- <string>group - *(NIX only) - The group name or ID that this entry belongs to.
- <string>target - *(NIX only) - For symlink entries, this is the symlink's target.
-
raw(<string>rawListing) - Emitted when a directory listing couldn't be parsed and provides you with the raw directory listing from the server.
-
end() - Emitted when the server has finished sending the directory listing, which may or may not be due to error.
-
success() - Emitted when the server says it successfully sent the entire directory listing.
-
error(<Error>err) - Emitted when an error was encountered while obtaining the directory listing.
-
pwd(<function>callback) - <boolean>success - Retrieves the current working directory. The callback has these parameters: the error (undefined if none) and a string containing the current working directory.
-
cwd(<string>newPath, <function>callback) - <boolean>success - Changes the current working directory to newPath. The callback has these parameters: the error (undefined if none).
-
cdup(<function>callback) - <boolean>success - Changes the working directory to the parent of the current directory. The callback has these parameters: the error (undefined if none).
-
get(<string>filename, <function>callback) - <boolean>success - Retrieves a file from the server. The callback has these parameters: the error (undefined if none) and a ReadableStream. The ReadableStream will emit 'success' if the file was successfully transferred.
-
put(<mixed>input, <string>filename, <function>callback) - <boolean>success - Sends a file to the server. The input
can be a ReadableStream or a single Buffer. The callback has these parameters: the error (undefined if none).
-
append(<mixed>input, <string>filename, <function>callback) - <boolean>success - Same as put, except if the file already exists, it will be appended to instead of overwritten.
-
mkdir(<string>dirname, <function>callback) - <boolean>success - Creates a new directory on the server. The callback has these parameters: the error (undefined if none) and a string containing the path of the newly created directory.
-
rmdir(<string>dirname, <function>callback) - <boolean>success - Removes a directory on the server. The callback has these parameters: the error (undefined if none).
-
delete(<string>entryName, <function>callback) - <boolean>success - Deletes a file on the server. The callback has these parameters: the error (undefined if none).
-
rename(<string>oldFilename, <string>newFilename, <function>callback) - <boolean>success - Renames a file on the server. The callback has these parameters: the error (undefined if none).
-
system(<function>callback) - <boolean>success - Retrieves information about the server's operating system. The callback has these parameters: the error (undefined if none) and a string containing the text returned by the server.
-
status(<function>callback) - <boolean>success - Retrieves human-readable information about the server's status. The callback has these parameters: the error (undefined if none) and a string containing the text returned by the server.
Extended
These are actions defined by later RFCs that may not be supported by all FTP servers.
-
size(<string>filename, <function>callback) - <boolean>success - Retrieves the size of the specified file. The callback has these parameters: the error (undefined if none) and a string containing the size of the file in bytes.
-
lastMod(<string>filename, <function>callback) - <boolean>success - Retrieves the date and time the specified file was last modified. The callback has these parameters: the error (undefined if none) and a Date instance representing the last modified date.
-
restart(<mixed>byteOffset, <function>callback) - <boolean>success - Sets the file byte offset for the next file transfer action (get/put/append). byteOffset can be an integer or string. The callback has these parameters: the error (undefined if none).