assurance-tunnel
assurance-tunnel
assurance-tunnel
assurance-tunnel

Use Javascript to test a Text file for existence and content.


  • Tech Staff

    You can use Javascript to read text files, you can also use Javascript to do error handling.

    So its possible to use Javascript to Try reading a file, and determine if the file is available (exists and is readable as text) by checking for an error.

    Here is a quick script that will tell you if a Text file exist, and if its Empty or Not.
    =========================================

    function main() {

    var state; // State or 0 = good txt, 1 = Empty, 2 = Read Error
    var txt;
    try { 
    txt = read(arguments[0]);
    state = 0;
    }
    catch(err) {
    // ERROR: unreadable file, or file doesn't exist
    txt = err.message;
    state = 2;
    }

    if (txt == ""){
    // text file exists but is empty
    state = 1;
    }

    return [txt,state];

    }

    =========================================

    @Michel how do we format code again.. its pretty script still installed?