Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I read a binary file with in javascript (Cscript.exe)?

Tags:

javascript

wsh

I think I can't read a binary file with the Scripting.FileSystemObject class. Can I do it with ADODB.Stream?

Something else?

I want to get an array of bytes.

thanks.

like image 501
Cheeso Avatar asked May 28 '10 03:05

Cheeso


1 Answers

It also works to read the file as a binary, and then use VBScript to transform the object that comes back (an array of variant) into a Javascript array of bytes. To do that you need to mix VBScript and Javascript together using a .wsf file. You still need ADODB.Stream.

<job id="Something">
  <script id="BFRHelper.vbs" language="VBScript">
    Public Function VbBinaryToArray(Binary)
        Dim i
        ReDim byteArray(LenB(Binary))
        For i = 1 To LenB(Binary)
            byteArray(i-1) = AscB(MidB(Binary, i, 1))
        Next
        VbBinaryToArray = byteArray
    End Function
  </script>

  <script language="JavaScript" id="BFR2.js">

    (function(){

        BinaryFileReader = {};

        var FileReadTypes = {
            adTypeBinary : 1,
            adTypeText   : 2
        };

        BinaryFileReader.ReadAllBytes = function(path)
        {
            var bs = WScript.CreateObject("ADODB.Stream");
            bs.Type = FileReadTypes.adTypeBinary;
            bs.Open();
            bs.LoadFromFile(path);
            var what = bs.Read;
            bs.Close();
            var array = VbBinaryToArray(what).toArray();
            // I find the length property is 1 higher than it ought to be
            var aL = array.length;
            array.length = aL -1;
            return array;
        };
    })();

    var content = BinaryFileReader.ReadAllBytes(path); 

  </script>
</job>
like image 114
Cheeso Avatar answered Sep 27 '22 21:09

Cheeso