Getting file size (JavaScript)

Last edited on

Introduction

The JavaScript interpreter in older versions of Squish does not provide the File.size() function for determining the size of a file.

One simple workaround for small text files that use the ASCII 7-bit encoding or the Unicode UTF-8 encoding is to simply read the entire file using the File object. If the text includes non-ASCII characters this will give a character count rather than a byte count, though.

If an actual byte count is required, or for large or non-text files, the best solution is to execute an external program that can output the file's size and capture the output.

Example of using an external Python interpreter

The following example starts the Python interpreter (usually the one shipping with Squish, if any) and lets it execute a little piece of Python code to retrieve the file size and then prints the file size.

The JavaScript interpreter in turn captures the output of the Python interpreter and converts it to an integer value.

function main() {
    var filename = "test.data";
    var size = fileSize(filename);
    test.log(filename + " = " + size + " bytes");
}

function fileSize(filename)
{
    var cmd = 'python -c "import os,sys;print os.path.getsize(sys.argv[1])"';
    var result = OS.capture(cmd + ' "' + filename + '"');
    return parseInt(result);
}
test.js