JS获取文件内容?

时间:2016-04-16 14:20:23

标签: javascript python xmlhttprequest httprequest

我正在使用JavaScript解析器创建一种新语言,而我正在尝试弄清楚如何获取本地文件的内容。我尝试使用/// <summary> /// Gets all public properties of an object and and puts them into dictionary. /// </summary> public static IDictionary<string, object> ToDictionary(this object instance) { if (instance == null) throw new NullReferenceException(); // if an object is dynamic it will convert to IDictionary<string, object> var result = instance as IDictionary<string, object>; if (result != null) return result; return instance.GetType() .GetProperties() .ToDictionary(x => x.Name, x => x.GetValue(instance)); } 请求,如下所示:

XMLHttp

但那没用。我的终端出现了这个错误:

var rawFile = new XMLHttpRequest();
rawFile.open("GET", "testing.txt", true);

我知道Python可以使用`(function (exports, require, module, __filename, __dirname) { var rawFile = new XMLHttpRequest(); ^` ReferenceError: XMLHttpRequest is not defined at Object.<anonymous> (/home/ubuntu/workspace/source.js:1:81) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Module.runMain [as _onTimeout] (module.js:441:10) `Process exited with code: 1` 模块获取文件内容:

subprocess

那么我应该切换到Python吗?或者有没有办法使用JavaScript?

1 个答案:

答案 0 :(得分:1)

你的意思是这样吗?

function readFile(evt) {
  var file = (evt.target.files)[0]; 
  var r = new FileReader();
  r.onload = (function(file) {
    return function(e) {
      var contents = e.target.result;
      alert(contents);
    };
  })(file);
  r.readAsText(file);
}
  
document.getElementById('fileinput').addEventListener('change', readFile, false);
<input type="file" id="fileinput" />