【问题标题】:Invalid callback error during call to node-fs-extra function copySync()调用 node-fs-extra 函数 copySync() 期间出现无效回调错误
【发布时间】:2021-01-30 07:45:43
【问题描述】:

当我尝试使用 Node.js 模块 node-fs-extra 的 copySync() 函数时出现错误。我不确定我做错了什么。这是我正在使用的代码:

fse = require('node-fs-extra');

function deploy(done) {
    try {
        fse.copySync('dir1', 'dir2');
        console.log('fse.copySync worked!')
    } catch (err) {
        console.log('fse.copySync threw an error');
        console.log(err);
    }

    done();
}

当这个函数运行时,我得到这个输出:

fse.copySync threw an error
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
    at maybeCallback (fs.js:145:9)
    at Object.exists (fs.js:212:3)
    at Object.copySync (/var/www/html/dev/plugin-biblica-online-bible/node_modules/node-fs-extra/lib/copy.js:62:23)
    at deployPlugin (/var/www/html/dev/plugin-biblica-online-bible/gulpfile.js:134:13)
    at deploy-plugin (/var/www/html/dev/plugin-biblica-online-bible/node_modules/undertaker/lib/set-task.js:13:15)
    at bound (domain.js:427:14)
    at runBound (domain.js:440:12)
    at asyncRunner (/var/www/html/dev/plugin-biblica-online-bible/node_modules/async-done/index.js:55:18)
    at processTicksAndRejections (internal/process/task_queues.js:79:11) {
  code: 'ERR_INVALID_CALLBACK'
}

它似乎在抱怨缺少回调函数。但是根据node-fs-extra documentation,copySync() 函数不接受回调函数。

我在使用其他同步函数(如 renameSync())时没有看到错误,我可以使用异步函数很好地复制目录:

fse = require('node-fs-extra');

function deploy(done) {
    fse.copy('dir1', 'dir2', {}, function (err) {
        if (err) {
            console.log('fse.copy threw an error');
            console.log(err);
            return;
        }
        console.log('fse.copy worked!')
    });

  done();
}

结果:

fse.copy worked!

如果重要,deploy() 函数将作为 Gulp 任务运行。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您的代码正在使用 node-fs-extra,它已被弃用。您正在阅读名为 fs-extra 的包的文档。

    安装fs-extra,然后使用:

    const fse = require('fs-extra'); // do this instead of require('node-fs-extra');
    // ...
    

    然后,您的代码就可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 2021-04-11
      • 2018-09-02
      • 2021-01-16
      相关资源
      最近更新 更多