The following is a short function to return a file size on a Linux system, run in the rhino shell:
function fsize(file){
var filesize = runCommand("stat","-c %s",file);
return filesize;
}
Running the function returns a value; e.g:
fsize('/etc/hosts');
returns a file size in bytes
But if I run:
var filesize = fsize(testfile);
the var filesize is "0" when output to the console.
Why is this happening, and how can it be fixed?
To examine variables, I used the function:
function output(strings){
print(strings);
}
A sample shell session, showing output:
js> var file = "/var/www/javascript/ProgressMon/progressmon.js" js> fsize(file); 683 0 js> var filesize = fsize(file); 683 js> filesize; 0 js> output(filesize); 0 js>
Examining the
runCommanddocumentation, it can be called in the following forms:The sample uses the second form, which prints the output to the terminal but does not capture it in any way that’s available to code. In other words,
fsize(testfile)does not return the file size, it prints it.The result returned by all forms is the exit status of the command, which is what gets assigned to
filesize.To capture output, you must use the third form and pass an object with an
outputproperty, which can be anjava.io.OutputStreamor a string. In this case, you probably want the latter, as that will cause program output to be appended to the property. The function can then callparseInton the output to get the size as a number, rather than a string.The system call might generate errors. To handle them within
fsize, you could print error messages and return a negative value to indicate an error. IfrunCommandmight throw an exception, the code could be wrapped in atry-catchblock.Alternatively, you could let code up the call-stack handle exceptions, and raise an exception for any error generated by the
runCommandcall .Note that instead of calling
output(filesize);to print the value offilesize, you can evaluate it directly: