FTP check with Node and JavaScript

Script to verify a FTP connection is available with a server, and commands may be remotely invoked.

FTP is useful to check a connection as part of a Node project that requires the use of FTP to exchange files between a local computer and a server, on a shared or dedicated hosting.

The script uses the jsftp module and works in asynchronous mode. First, we test whether the connection is possible with the stat command. It returns an error if the server is unreachable or denies the connection.

If the connection is established, we try another command, reading the last modified date of a file, whose you specify the name and path.

You may modify the script to test other command, the exhaustive list of possible commands can be read in the jsftp.js file.

The script runs with the following command:

node testftp.js parameters 

The following parameters are required:

-l   followed by the login
-p   followed by the password
-f   followed by the FTP URL.
filename with full path from the root of the public sub-directory.

Example

 node testftp.js -lusername -pxxxxxx -fftp.example.com www/myfile.html

Source code of the script:

var JSFtp = require("jsftp")

function main(argc,argv)
{
    processCommand(argc, argv.slice(1))

    OPTIONS={"host":server,"port":21,"user":user,"pass":pass,"debugMode":true}

    var connection = new JSFtp(OPTIONS)
    console.log("Checking FTP on "+ server)       
    connection.raw.stat(function(err, data) {
        if(err) {
            console.log("Server not available through FTP. Error:" + err)
            return
        }
        console.log("Server OK.")

        console.log("Checking date of " + filename)  

        connection.raw.mdtm(filename, function(err, data) {
            if(err) {
                console.log("Date not returned. Error: " + err)
                return
            }    
            console.log("Date/Time: " + data.text.substr(4))
            console.log("Data returned:")
            console.log(JSON.stringify(data))
            connection.raw.quit(function(err, data) {
                console.log("Bye!")
                process.exit(1)
            })
        })
    })
}    

main(process.argv.length-1,process.argv.slice(1))

Download the full script:

Remember to install jsftp before running the script (npm install jsftp).