Skip to content

Instantly share code, notes, and snippets.

@bigsan
Created October 26, 2012 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigsan/3958016 to your computer and use it in GitHub Desktop.
Save bigsan/3958016 to your computer and use it in GitHub Desktop.
TypeScript: readFile function in io.ts
readFile: function(path) {
try {
var file = fso.OpenTextFile(path);
var bomChar = !file.AtEndOfStream ? file.Read(2) : '';
var str = bomChar;
if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF)
|| (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) {
// Reopen the file as unicode
file.close();
file = fso.OpenTextFile(path, 1 /* IOMode.ForReading */, false /* Create */, -1 /* Format.TristateUseUnicode */);
str = '';
// ReadAll will helpfully throw an error if this is a 0-byte file
if (!file.AtEndOfStream) {
str = file.ReadAll();
}
file.close();
}
else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) {
// Reopen the file as utf-8
file.Close();
var stream = new ActiveXObject("ADODB.Stream");
stream.Mode = 3; /* adModeReadWrite = 3*/
stream.Type = 2; /* adTypeText = 2 */
stream.CharSet = "utf-8";
stream.Open();
stream.LoadFromFile(path);
str = '';
if (!stream.EOS) {
str = stream.ReadText();
}
stream.Close();
}
else {
if (!file.AtEndOfStream) {
str += file.ReadAll();
}
file.close();
}
return <string>str;
}
catch (err) {
throw new Error("Error reading file \"" + path + "\": " + err.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment