【问题标题】:Is there a way to read a text file synchronously (in JS node)? [duplicate]有没有办法同步读取文本文件(在 JS 节点中)? [复制]
【发布时间】:2020-12-29 20:54:40
【问题描述】:

这是我的示例代码:

var dicWords = []
function ReadFile()
{
    var fs = require('fs')
    fs.readFile('words_alpha_sorted.txt', (err, data) =>{
        if (err){
            console.log(err);
            return;
        }
        data = String(data)
        dicWords = data.split(/\r?\n/);
    })
}
function DoStuffWithFile();
{
    //do stuff with the variable dicWords
}
function main()
{
    ReadFile();
    DoStuffWithFile();
}

我怎样才能读取文件,等待它被完全读取,然后执行其余代码,以便在调用 DoStuffWithFile 时 dicWords 不是空数组?使用 JS(节点)。我想从主函数调用 DoStuffWithFile,而不是 ReadFile。注意-:主函数实际上并不是主函数,而是文件管理发生的地方。

【问题讨论】:

    标签: node.js synchronous file-management


    【解决方案1】:

    您可以为此使用readFileSync function

        const data = fs.readFileSync('words_alpha_sorted.txt');
    

    但异步函数几乎总是更好的解决方案。同步方法会在未知的时间内停止 Javascript 的执行(与 JS 代码相比,这似乎是一个永恒的时间),而异步文件系统函数是并行运行的。

    您可以利用异步/等待友好的 Promise 方法来做:

    var dicWords = []
    async function ReadFile()
    {
        var fs = require('fs').promises
        let data = await fs.readFile('words_alpha_sorted.txt')
        data = String(data)
        dicWords = data.split(/\r?\n/);
    }
    function DoStuffWithFile();
    {
        //do stuff with the variable dicWords
    }
    async function main()
    {
        await ReadFile();
        DoStuffWithFile();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多