简体   繁体   English

Javascript fs.readfile() 不保存到变量

[英]Javascript fs.readfile() Not Saving to Variable

I am trying to use javascrtipt fs.readfile() , but I can't get it to store what it has read to a variable.我正在尝试使用 javasccrtipt fs.readfile() ,但我无法让它将它读取的内容存储到变量中。 Here is my code:这是我的代码:

const fs = require('fs')

var importantFinalCode = "waiting..."

fs.readFile("\pvMLTest.txt", "utf8", 
function(err, data){
  importantFinalCode = JSON.parse(data)
})


do {
  console.log("...")
} while (importantFinalCode == "waiting...")

console.log(importantFinalCode)

For some reason, it just infinitely logs ... , even though the function says to set the variable importantFinalCode to what it is reading.出于某种原因,它只是无限记录... ,即使 function 说将变量importantFinalCode设置为它正在读取的内容。 Do I need to make it a global variable?我需要将其设为全局变量吗? If so, how?如果是这样,怎么做?

By the way, here is the file it is reading ( pvMLTest.txt ):顺便说一下,这是它正在读取的文件( pvMLTest.txt ):

[["1", "2", "3"], ["3", "2", "4"]]

Thanks.谢谢。

The following code is an infinite loop that takes up all of the event loop - therefore your script never completes:以下代码是占用所有事件循环的无限循环 - 因此您的脚本永远不会完成:

do {
  console.log("...")
} while (importantFinalCode == "waiting...")

You can put the console into fs.readFile callback to be executed after file reading complete:您可以将控制台放入fs.readFile回调中以在文件读取完成后执行:

const fs = require('fs')

var importantFinalCode = "waiting..."

fs.readFile("pvMLTest.txt", "utf8", 
function(err, data){
  importantFinalCode = JSON.parse(data)
  console.log(importantFinalCode)
})

If your file is really big and you want to see the progress of its loading then you can use streams to read it:如果您的文件非常大并且您想查看其加载进度,那么您可以使用流来读取它:

const fs = require('fs');
const sourceFile = 'pvMLTest.txt';

var importantFinalCode = "waiting...";
console.log(importantFinalCode);

var data = '';
const readStream = fs.createReadStream(sourceFile);

readStream.on('data', function(buffer) {
    console.log('...');
    data += buffer;
});
readStream.on('end', function() {
    importantFinalCode = JSON.parse(data)
    console.log(importantFinalCode);
});

By doing this:通过做这个:

fs.readFile("\pvMLTest.txt", "utf8", 
function(err, data){
  importantFinalCode = JSON.parse(data)
})

You are telling JavaScript to execute the callback function function(err, data){ later.您告诉 JavaScript 稍后执行回调 function function(err, data){ Later means whens the data arrives, and it also means when the current callstack is empty. later 表示数据何时到达,也表示当前调用栈何时为空。 By doing this:通过做这个:

do {
  console.log("...")
} while (importantFinalCode == "waiting...")

You are maintaining the current callstack alive forever.您将永远维持当前的调用堆栈。 In short, the current callstack waits for the data, but the data callback waits for the current callstack to be empty.简而言之,当前调用栈等待数据,而数据回调等待当前调用栈为空。 This is a kind of deadlock.这是一种僵局。

Whatever you want to do with the data, it must go inside the callback.无论您想对数据做什么,都必须在回调内部 go 。

I suggest you read about the JavaScript's runtime specification which will help you understand why your code doesn't work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop我建议你阅读 JavaScript 的运行时规范,这将帮助你理解为什么你的代码不起作用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Fixed your issue.修复了您的问题。 This was running an infinite loop due to the scope of the callback function within fs.readFile .由于 fs.readFile 中的回调 function 的fs.readFile ,这是一个无限循环。 Once you added your txt file data to the variable within the readFile function, it belonged to that function.将 txt 文件数据添加到 readFile function 中的变量后,它就属于该 function。

The do / while loop was accessing your gloabally assigned variable, instead of the one within the function. do / while 循环正在访问您全局分配的变量,而不是 function 中的变量。

Moving your loop into the callback function, fixed the issue.将循环移动到回调 function 中,解决了这个问题。 But not sure why you would have let importantFinalCode = "waiting..." because as soon as the readFile function runs, it changes the value of importantFinalCode.但不确定为什么let importantFinalCode = "waiting..."因为一旦 readFile function 运行,它就会改变 importantFinalCode 的值。

const fs = require('fs')

let importantFinalCode = "waiting..."

fs.readFile("\pvMLTest.txt", "utf8", function (err, data) {
    if (err) {
        console.log(err)
    }
    importantFinalCode = data

    do {
        console.log("...")
    } while (importantFinalCode === "waiting...");
    console.log(importantFinalCode)
})

If you wanted to present the user with "waiting..." you could use a for loop like:如果您想向用户展示"waiting..." ,您可以使用 for 循环,例如:

const fs = require('fs')

for (let i = 0; i <= 10; i++) {
    let importantFinalCode = "waiting..."
    console.log(importantFinalCode)
}

fs.readFile("\pvMLTest.txt", "utf8", function (err, data) {
    if (err) {
        console.log(err)
    }
    importantFinalCode = data

    console.log(importantFinalCode)
})

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

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