2

These are the functions which load file and write file. I used JavaScript and XPCOM for these operations. You can use these functions in iMacros JavaScript file.

Edit: These functions work best in iMacros version 8.9.7 and corresponding Firefox. The later versions of iMacros addon don't support JavaScript. Also it's best to use Firefox 47 with disabled updates. And you can use latest Pale Moon browser with addon 8.9.7 . If there is a content in file the WriteFile function simply adds data in new line.

//This function load content of the file from a location
//Example: LoadFile("C:\\test\\test.txt")

function LoadFile(path) {

    try {
        Components.utils.import("resource://gre/modules/FileUtils.jsm");

        var file = new FileUtils.File(path);

        file.initWithPath(path);
        var charset = 'UTF8';
        var fileStream = Components.classes['@mozilla.org/network/file-input-stream;1']
            .createInstance(Components.interfaces.nsIFileInputStream);
        fileStream.init(file, 1, 0, false);
        var converterStream = Components.classes['@mozilla.org/intl/converter-input-stream;1']
            .createInstance(Components.interfaces.nsIConverterInputStream);
        converterStream.init(fileStream, charset, fileStream.available(),
            converterStream.DEFAULT_REPLACEMENT_CHARACTER);
        var out = {};
        converterStream.readString(fileStream.available(), out);
        var fileContents = out.value;
        converterStream.close();
        fileStream.close();

        return fileContents;
    } catch (e) {
        alert("Error " + e + "\nPath" + path)
    }

}

//This function writes string into a file

function WriteFile(path, string) {
    try {
        //import FileUtils.jsm
        Components.utils.import("resource://gre/modules/FileUtils.jsm");
        //declare file
        var file = new FileUtils.File(path);

        //declare file path
        file.initWithPath(path);

        //if it exists move on if not create it
        if (!file.exists()) {
            file.create(file.NORMAL_FILE_TYPE, 0666);
        }

        var charset = 'UTF8';
        var fileStream = Components.classes['@mozilla.org/network/file-output-stream;1']
            .createInstance(Components.interfaces.nsIFileOutputStream);
        fileStream.init(file, 18, 0x200, false);
        var converterStream = Components
            .classes['@mozilla.org/intl/converter-output-stream;1']
            .createInstance(Components.interfaces.nsIConverterOutputStream);
        converterStream.init(fileStream, charset, string.length,
            Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);

        //write file to location
        converterStream.writeString(string + "\r\n");
        converterStream.close();
        fileStream.close();

    } catch (e) {
        alert("Error " + e + "\nPath" + path)
    }

}


//this function removes file from location
function RemoveFile(path) {

    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    //file.initWithPath("c:\\batstarter6_ff.cmd");
    file.initWithPath(path);

    /*
    var file = IO.newFile(path, name);

     */
    file.remove(false);

}


// Download a file form a url.

function saveFile(url) {

    try {

        // Get file name from url.
        var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onload = function () {
            var a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
            a.download = filename; // Set the file name.
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            delete a;
        };
        xhr.open('GET', url);
        xhr.send();

    } catch (e) {
        alert("Error " + e)
    }
}


/*
This function runs file from given path
 */

function RunFile(path) {

    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    //file.initWithPath("c:\\batstarter6_ff.cmd");
    file.initWithPath(path);
    file.launch();

}


//this function downloads a file from url
function downloadFile(httpLoc, path) {
    try {
        //new obj_URI object
        var obj_URI = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null);

        //new file object
        var obj_TargetFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);

        //set file with path
        obj_TargetFile.initWithPath(path);
        //if file doesn't exist, create
        if (!obj_TargetFile.exists()) {
            obj_TargetFile.create(0x00, 0644);
        }

        //new persitence object
        var obj_Persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);

        // with persist flags if desired
        const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
        const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
        obj_Persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
        /*
        var privacyContext = sourceWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
        .getInterface(Components.interfaces.nsIWebNavigation)
        .QueryInterface(Components.interfaces.nsILoadContext);*/

        //save file to target
        obj_Persist.saveURI(obj_URI, null, null, null, null, obj_TargetFile, null);
    } catch (e) {
        alert(e);
    }
}



//This function prompts user to select file from folder and use it

function PickFile(title) {

    const nsIFilePicker = Components.interfaces.nsIFilePicker;

    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
    fp.init(window, title, nsIFilePicker.modeOpen);
    fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);

    var rv = fp.show();
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
        var file = fp.file;
        // Get the path as string. Note that you usually won't
        // need to work with the string paths.
        var path = fp.file.path;
        // work with returned nsILocalFile...
        return path;

    }

}

//This function prompts user to select folder from folder and use it
function PickFolder(title) {

    var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
    picker.appendFilters(Components.interfaces.nsIFilePicker.filterAll);
    //folder
    picker.init(window, title, Components.interfaces.nsIFilePicker.modeGetFolder);
    //or file
    // picker.init (window, "Choice file", Components.interfaces.nsIFilePicker.modeOpen);
    if (picker.show() == Components.interfaces.nsIFilePicker.returnOK) {

        return picker.file.path;
    } else {
        return false;
    }
}



//this function offers a set of options to select from
//items is an array of options
//title is the dialog title
//qustion is a question asked to user.

function Select(items, title, question) {

    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
        .getService(Components.interfaces.nsIPromptService);

    //var items = ["Articles", "Modules", "Both"]; // list items

    var selected = {};

    var result = prompts.select(null, title, question, items.length,
            items, selected);

    // result is true if OK was pressed, false if cancel. selected is the index of the item array
    // that was selected. Get the item using items[selected.value].

    var selected = items[selected.value];

    return selected;

}

Edit: I am also adding iMacros version 8.9.7 addon to download because version 10 doesn't support JavaScript http://download.imacros.net/imacros_for_firefox-8.9.7-fx.xpi

Edit1: I added some more useful functions for iMacros.

edinvnode
  • 3,497
  • 7
  • 30
  • 53
  • 1
    Hum, OK, Thanks for sharing... You should/could mention in which FCI/Version(s) you've tested it... => I guess this probably only works in v8.9.7 for FF (+ FF55 or PM28), and "maybe" in v9.0.3...(?) - "Interesting" would be if that "Construction" can be adapted to be used in v10.0.2 for FF 'Free' or v10.0.5 for CR 'Free' to bypass the 'SAVEAS' Limitation for the 'Free' Versions...? - Are there any Differences/Advantages upon using the much more straightforward 'SAVEAS TYPE=EXTRACT' Syntax...? (... which for example can only append some new Content... Can your Syntax edit an existing File...?) – chivracq Jul 01 '19 at 17:08
  • Well, "edit" an existing File and replace it with the new Content, or add some New Content at a specific location in the File, or at the beginning...? (This can already be done using '!DATASOURCE' + '!COLn' for a '.CSV' or 'URL GOTO' + 'EXTRACT' for a '.TXT', then 'EVAL()' or '.js' for the Data Manipulation', then 'FILEDETELE' + 'SAVEAS', but this is always a bit cumbersome..., (especially for a '.CSV), and only doable for relatively "small" Files...) – chivracq Jul 01 '19 at 17:22
  • Thread linked to (and quoted) in some "related" Thread on the iMacros Forum that happened to be bumped recently... (=> using 'xmlhttprequest'): https://forum.imacros.net/viewtopic.php?f=11&t=26869&p=82599#p82599 – chivracq Jul 01 '19 at 18:05
  • 1
    Added requested edits. – edinvnode Jul 02 '19 at 08:14
  • OK, good... v8.9.7 for FF works fine in FF v55.0.3 also btw, (which is the FF Version I "recommend" on the iMacros Forum (and that I use myself)), you don't have to stick to FF47. - But OK then, this Syntax does actually the same like 'SAVEAS TYPE=EXTRACT', which is much easier to use, I would think... – chivracq Jul 02 '19 at 17:21
  • Thread cross-linked on the iMacros Forum by Advanced User [@]thecoder2012 as "Inspiration" for some related Func... (=> to check if a File exists). - And a late (+1) from me, Site always buggy, only half of the Func works in PM26 my Default Browser, (since about 2 years...!), one week Funcs don't work, then they work again, then they get broken again, ah-ah...!, [...] – chivracq Dec 09 '19 at 04:44
  • [...] ... currently 'Comments' + '+/-1' both don't work, tja...!, I had to use FF55 now to be able to post this Comment, while Comments were probably still working in July 2019, 5 months ago... - Post on the iMacros Forum: https://forum.imacros.net/viewtopic.php?f=11&t=29932&p=84245#p84238 - Grr, Buggy Site again, "Comment too long by xxx Chars"..., splitting it 2... – chivracq Dec 09 '19 at 04:45

0 Answers0