简体   繁体   English

JS获取文件内容?

[英]JS Get File Contents?

I'm creating a new language, with a JavaScript parser, and I'm currently trying to figure out how to get a local file's contents. 我正在使用JavaScript解析器创建一种新语言,并且目前正在尝试弄清楚如何获取本地文件的内容。 I tried using a XMLHttp request which looked like this: 我尝试使用看起来像这样的XMLHttp请求:

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

But that didn't work. 但这没有用。 I got this error in my terminal: 我在终端中收到此错误:

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

I know Python can get a file's contents using the subprocess module: 我知道Python可以使用subprocess模块获取文件的内容:

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

So should I just switch over to Python instead? 那我应该改用Python吗? Or is there a way to use JavaScript? 还是有使用JavaScript的方法?

You mean like this ? 你的意思是这样吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM