javascript - JS获取文件内容?

标签 javascript python xmlhttprequest httprequest

我正在使用 JavaScript 解析器创建一种新语言,目前我正在尝试找出如何获取本地文件的内容。我尝试使用 XMLHttp 请求,如下所示:

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

但这没有用。我在终端中收到此错误:

`(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`  

我知道Python可以使用subprocess模块获取文件的内容:

import subprocess
with open(file, 'r') as myfile:
data=myfile.read().replace('\n', '')`  

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

最佳答案

你的意思是这样吗?

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" />

关于javascript - JS获取文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36665322/

相关文章:

javascript - anchor 标记内的 Div 不占用整个宽度? HTML 和 CSS

python - 减少 numba @jitclass 编译时间(使用缓存?)

python - 将图像与图形边框对齐时,OffsetImage 在屏幕上和 PDF 中显示不同

cookies - 从 qml 获取/设置 cookie

javascript - 如何更新 MooTools Request.HTML 调用中的多个元素

javascript - 使用 Javascript 计算两个日期之间的持续时间

javascript根据条件从嵌套的对象数组返回属性值

Python NumPy 向量化

javascript - 运行混合内容有什么解决方法吗?

javascript - 如何在同一页面上使用具有相同 ID 的多个(动态)切换按钮?