hakeの日記

Windows環境でプログラミングの勉強をしています。

javascript Windows環境でローカルPCからテキストファイルの読み込み

一括で読み込む場合と一行ずつ読み込む場合を記載。

<!DOCTYPE html>
<html lang='ja'>
<head>
	<meta http-equiv="content-type" content="text/html; charset=shift_jis">
	<script type="text/javascript">

	var file;

	// http://msdn.microsoft.com/ja-jp/library/cc428044.aspx
	// OpenTextFile メソッド
	var forReading, forWriting, forAppending
	var tristateUseDefault, tristateTrue, tristateFalse
	//第2引数 ファイル入出力モード
	forReading   = 1;
	forWriting   = 2;
	forAppending = 8;

	// 一括で読み込み
	// https://msdn.microsoft.com/ja-jp/library/cc428049.aspx
	function readAll(filename) {
		var fsi = new ActiveXObject('Scripting.FileSystemObject');
		var file = fsi.OpenTextFile(filename, forReading);
		var s = file.ReadAll();
		file.Close();
		alert(s);
	}

	// 一行ずつ読み込み
	// https://msdn.microsoft.com/ja-jp/library/cc428051.aspx
	// https://msdn.microsoft.com/ja-jp/library/cc428128.aspx
	function readLine(filename) {
		var fsi = new ActiveXObject('Scripting.FileSystemObject');
		var file = fsi.OpenTextFile(filename, forReading);
		var s;
		while(!file.AtEndOfStream){
			s = file.ReadLine();
			alert(s);
		}
		file.Close();
	}

	file = 'C:\\work\\javascript\\test.txt'
	readAll(file);
	readLine(file);

	</script>
</head>
</html>