How to read and write binary files using jscript
How to read and write binary files using jscript
This article describes how to read and write binary files in jscript. It involves the use of ActiveXObject objects in javascript and has some reference value. For more information, see
This document describes how jscript reads and writes binary files. Share it with you for your reference. The specific implementation method is as follows:
Var bin = new Array (256 );
For (var I = 0; I <256; I ++ ){
Bin [I] = String. fromCharCode (I );
}
Function TestWrite (){
Var Stream = new ActiveXObject ("ADODB. Stream ");
Var adTypeBinary = 1, adTypeText = 2;
Stream. Type = adTypeText;
Stream. CharSet = "iso-8859-1 ";
Stream. Open ();
// Stream. WriteText ("\ x00 \ x01 \ x02 \ xff ");
For (var I = 0; I <256; I ++ ){
Stream. WriteText (String. fromCharCode (I ));
// Stream. WriteText (bin [I]);
}
Stream. SaveToFile ("c: \ windows \ temp \ test. bin", 2 );
Stream. Close ();
Stream = null;
}
Function BinaryFile (filepath ){
Var adTypeBinary = 1, adTypeText = 2;
Var adSaveCreateNotExist = 1, adSaveCreateOverWrite = 2;
Var adReadAll =-1, adReadLine =-2;
This. path = filepath;
This. WriteAll = function (content ){
Var Stream = new ActiveXObject ("ADODB. Stream ");
Stream. Type = adTypeText;
Stream. CharSet = "iso-8859-1 ";
Stream. Open ();
Stream. WriteText (content );
Stream. SaveToFile (this. path, adSaveCreateOverWrite );
Stream. Close ();
Stream = null;
}
This. ReadAll = function (){
Var Stream = new ActiveXObject ("ADODB. Stream ");
Stream. Type = adTypeText;
Stream. CharSet = "iso-8859-1 ";
Stream. Open ();
Stream. LoadFromFile (this. path );
Var content = Stream. ReadText (adReadAll );
Stream. Close ();
Stream = null;
Return content;
}
}
Example:
Var crFolder = 'C:/Temp/cr'
Var bf1 = new BinaryFile (crFolder + "/PCDV0026.JPG ");
Var bf2 = new BinaryFile (crFolder + "/PCDV0026_.JPG ");
Bf2.WriteAll (bf1.ReadAll ());
I hope this article will help you design javascript programs.