Html 在 Javascript 中同步读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17068610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a file synchronously in Javascript
提问by Laila
I would like to read a file and convert it into a base64 encoded string using the FileReader object. Here's the code I use :
我想读取一个文件并使用 FileReader 对象将其转换为 base64 编码的字符串。这是我使用的代码:
var reader = new FileReader(); reader.onloadend = function(evt) { // file is loaded result_base64 = evt.target.result; }; reader.readAsDataURL(file);
But in this case, I get the result of the conversion in the event handler (onLoadEnd event). I would like a synchronous method. Is there a way the "readAsDataURL" method can return directly the value of the 'result_base64' variable ?
但是在这种情况下,我在事件处理程序(onLoadEnd 事件)中获得了转换结果。我想要一个同步方法。“readAsDataURL”方法有没有办法直接返回“result_base64”变量的值?
采纳答案by David Fari?a
Synchronous tasks (blocking) are generally bad. If there is no real reason to do that asynchronously, I strongly recommend you to use the event callback.
同步任务(阻塞)通常很糟糕。如果没有真正的理由异步执行此操作,我强烈建议您使用事件回调。
Imagine your file is broken and the HTML5 api cant read, it wont give you the result. It would break your code and block the site. Or, someone could select a 10GB file, which would freeze your HTML page until the file is completely loaded. With that asynchronous event handler your able to catch possible errors.
想象一下你的文件坏了,HTML5 api 无法读取,它不会给你结果。它会破坏您的代码并阻止该站点。或者,有人可以选择一个 10GB 的文件,这会冻结您的 HTML 页面,直到文件完全加载。使用该异步事件处理程序,您可以捕获可能的错误。
To work around limitations with callbacks, i use a simple trick:
为了解决回调的限制,我使用了一个简单的技巧:
var ready = false;
var result = '';
var check = function() {
if (ready === true) {
// do what you want with the result variable
return;
}
setTimeout(check, 1000);
}
check();
var reader = new FileReader();
reader.onloadend = function(evt) {
// file is loaded
result = evt.target.result;
ready = true;
};
reader.readAsDataURL(file);
the check function, checks every second if the ready flag variable is set to true. If so, you can be sure the result is available.
check 函数每秒检查一次就绪标志变量是否设置为 true。如果是这样,您可以确定结果可用。
It may not be best practice to do so, but i made a webapp using this technique about 30 times with more than 10 setTimeouts at the same time running, and experienced no problem until now.
这样做可能不是最佳实践,但我使用这种技术制作了一个 webapp 大约 30 次,同时运行了 10 多个 setTimeout,并且直到现在都没有遇到任何问题。
回答by John Weisz
You can use the standard FileReaderSync, which is a simpler, synchronous, blocking version of the FileReader API, similar to what you are already using:
您可以使用标准FileReaderSync,它是 FileReader API 的更简单、同步、阻塞版本,类似于您已经在使用的:
let reader = new FileReaderSync();
let result_base64 = reader.readAsDataURL(file);
console.log(result_base64); // aGV5IHRoZXJl...
Keep in mind though that this is only available in worker threads, for obvious reasons.
请记住,由于显而易见的原因,这仅在工作线程中可用。
If you need a solution for the main thread that "reads like" a synchronous API, you can wrap the async FileReader in a promise and use async functions (you might need to transpile):
如果您需要一个“读起来像”同步 API 的主线程解决方案,您可以将异步 FileReader 包装在承诺中并使用异步函数(您可能需要转译):
async function readFileAsDataURL(file) {
let result_base64 = await new Promise((resolve) => {
let fileReader = new FileReader();
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsDataURL(file);
});
console.log(result_base64); // aGV5IHRoZXJl...
return result_base64;
}
回答by Stephen Wylie
In Node.js, Use execSync
from child_process
and have the shell read it in for you synchronously. Redirect the output of this child process to the parent.
在 Node.js 中,使用execSync
fromchild_process
并让 shell 为您同步读取它。将此子进程的输出重定向到父进程。
// Don't forget to use your favorite encoding in toString()
var execSync = require('child_process').execSync;
var fileContents = execSync('cat path/to/file.txt', {stdio: "pipe"}).toString();
I'll gladly accept your nomination for the UUOC award. ;)
我很乐意接受你的 UUOC 奖提名。;)
回答by Jonathan Thurft
To read the contents of a file synchronously use fs.readFileSync
要同步读取文件的内容,请使用fs.readFileSync
var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);
fs.createReadStreamcreates a ReadStream.
回答by AtanuCSE
Late in the business, but may be this will help someone. We can just simply take the fight outside of the room.
在业务后期,但可能这会帮助某人。我们可以简单地在房间外进行战斗。
var file = $('#myfile')[0].files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
//console.log(this.result);
handle(this.result);
};
reader.readAsText(file);
function handle(temp_lines) {
var inputLines=new Array();
var lines = temp_lines.split('\n');
for(var line = 0; line < lines.length; line++) {
console.log(lines[line]);
inputLines[line]=lines[line];
}
}