为什么我的readFileSync函数没有执行

为什么我的readFileSync函数没有执行

本文介绍了为什么我的readFileSync函数没有执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Node中的文件读取.这是我的代码:

I'm trying to read from a file in Node. Here is my code:

const cheerio = require('cheerio');

var fs = require('fs');
var path = process.argv[2];

var glossArr = []

fs.readFileSync(path, {encoding: "utf8"}, function (err, markup){
    console.log('function executing')
    if (err) throw err;
    const $ = cheerio.load(markup);
    var glossar = $('body').children().last();
    var index = $('body').children().last().prev();


    glossar.children().children().children().each(function(i, elem) {
    var obj = {};
        var container = $(this).children();

    var unter = container.children();
    var begriff = unter.first().text();
    var text = unter.last().text();
    obj[begriff] = text;
    obj['file'] = path;
    glossArr.push(obj)
    });

});

console.log('done reading file...')

var glossString = JSON.stringify(glossArr)
var result = 'export default ' + glossString

fs.writeFileSync('./data/data.js', result)

由于某种原因,readFileSync根本不执行.唯一记录的是已完成读取文件..."

For some reason, the readFileSync doesn't execute at all. The only thing that's logged is 'done reading file...'

但是,当我将其更改为 readFile()(而不是同步)时,该函数将按预期执行并运行.我想念什么?

However, when I changed it to readFile() (instead of sync), the function executes and works as expected. What am I missing?

推荐答案

readFileSync 不接受回调参数,因为它是同步的.您需要更改代码,以将代码从回调内移动到同步功能下:

readFileSync doesn't accept a callback parameter because it's synchronous. You need to change your code to move the code from within the callback to beneath the synchronous function:

var markup = fs.readFileSync(path, {encoding: "utf8"});
const $ = cheerio.load(markup);
// ...

澄清一下,正在执行 readFileSync ,只是您对结果不做任何事情,并且您的回调参数也被忽略了.

To clarify, the readFileSync is being executed, it's just that you aren't doing anything with the result and your callback parameter is being ignored.

这篇关于为什么我的readFileSync函数没有执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 07:01
查看更多