Read file with Rhino
Asked Answered
P

2

6

Is it possible with Rhino Server-side Javascript to locate and read the contents of an arbitrary local file?

Photocopier answered 30/8, 2011 at 20:16 Comment(0)
B
13

Sure is.

from interpreter:

js> readFile('./tmp.txt');

or in code:

var filesz = readFile('./tmp.txt');
Brnaba answered 30/8, 2011 at 20:21 Comment(0)
B
1

For those that want to read a binary file using charCodeAt on the results from readFile don't return the expected values for bytes above 0x7F. If you want to read a binary file, it works better to do something like:

var readBinaryFile=function(path){
    var file=java.io.RandomAccessFile(path,'r');
    var bytes=java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, file.length());
    file.read(bytes);
    file.close();
    return bytes;
}

Which will give you a byte array.

Warning: When you read the bytes from that array it will treat them as signed i.e. 0xFF is interpreted as -1. (If you know an easy way to fix this please comment.)

Britton answered 2/3, 2017 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.