niedenzu

Hints and tricks for developers

Martins Amazon Wunschliste

convert ANSI to UTF-8 using JavaScript 28. June 2012


 var adTypeBinary = 1;  
 var adTypeText  = 2;  
 var bOverwrite = true;  
 var bAsASCII = false;  
 var oFS = new ActiveXObject("Scripting.FileSystemObject");  
 var sFiNa = "OPM_Mitarbeiter.csv";  
 var sFrom = "Windows-1252";  
 var sFFSpec = oFS.GetAbsolutePathName( sFiNa);  
 var oTo = new ActiveXObject( "ADODB.Stream" );  
 var sTo = "utf-8";  
 var sTFSpec = oFS.GetAbsolutePathName( sFiNa + "-utf8.txt" );  
 WScript.Echo("File name:"+sTFSpec);  
 if (oFS.FileExists( sTFSpec )) {oFS.DeleteFile(sTFSpec);};  
 var oFrom = new ActiveXObject( "ADODB.Stream" );  
 oFrom.Type = adTypeText;  
 oFrom.Charset = sFrom;  
 oFrom.Open();  
 oFrom.LoadFromFile(sFFSpec);  
 WScript.Echo(oFrom.Size + " Bytes in " + sFFSpec);  
 var oTo = new ActiveXObject( "ADODB.Stream" );  
 oTo.Type  = adTypeText;  
 oTo.Charset = sTo;  
 oTo.Open();  
 oTo.WriteText(oFrom.ReadText());  
 WScript.Echo(oTo.Size + " Bytes in " + sTFSpec);  
 var adSaveCreateNotExist = 1;  
 WScript.Echo(sTFSpec);  
 oTo.SaveToFile(sTFSpec , adSaveCreateNotExist);  
 oFrom.Close();  
 oTo.Close();  
 WScript.Echo("Das Programm ist nicht abgestürzt"); 
No Comments on convert ANSI to UTF-8 using JavaScript
Categories: Uncategorized

Remove BOM in Javascript

Sometimes you need to remove the BOM from a UTF-8 File. E.g. because Java can’t deal with it. So if you use Windows as your OS you can use the follwing JavaScript.
Simple execute it in a console.

 // Removes the Byte Order Mark - BOM from a text file with UTF-8 encoding  
 // The BOM defines that the file was stored with an UTF-8 encoding.  
 function RemoveBOM(filePath) {  
     // Create a reader and a writer  
         var writer,reader, fileSize;  
         var writer = new ActiveXObject("Adodb.Stream");  
         var reader = new ActiveXObject("Adodb.Stream");  
     // Load from the text file we just wrote  
         reader.Open();  
         reader.LoadFromFile( filePath);  
     // Copy all data from reader to writer, except the BOM  
         writer.Mode=3;  
         writer.Type=1;  
         writer.Open();  
         reader.position=5;  
         reader.copyto(writer,-1);  
     // Overwrite file  
         writer.SaveToFile(filePath,2);  
     // Return file name  
         RemoveBOM = filePath;  
     // Kill objects  
         var writer = null;  
         var reader = null;  
 }  
 RemoveBOM("OPM_Mitarbeiter.csv-utf8.txt");  
cscript bomremover.js
No Comments on Remove BOM in Javascript
Categories: Uncategorized
Martin Rocks