【问题标题】:TypeError [ERR_INVALID_CALLBACK]: Callback must be a functionTypeError [ERR_INVALID_CALLBACK]:回调必须是函数
【发布时间】:2018-10-30 12:07:07
【问题描述】:

我想编写一个脚本来向 angular webpack 应用程序添加新规则,如下所示。有时代码部分执行,有时会出错。

const fs = require('fs');
const commonCliConfig = 'node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/common.js';
const pug_rule = "\n{ test: /\\.pug$/, loader: ['raw-loader' , 'pug-html-loader' ]},";
var configText = "";
fs.readFile(commonCliConfig, function(err, data) {
    if (err) throw err;
    configText = data.toString();
    if (configText.indexOf(pug_rule) > -1) { return; }
    const position = configText.indexOf('rules: [') + 8;
    const output = [configText.slice(0, position), pug_rule, configText.slice(position)].join('');
    const file = fs.openSync(commonCliConfig, 'r+');
    fs.writeFile(file, output);
    fs.close(file);
});


Terminal node pug-rule.js
fs.js:148
    throw new ERR_INVALID_CALLBACK();
    ^

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
    at makeCallback (fs.js:148:11)
    at Object.fs.close (fs.js:520:20)
    at path/pug-rule.js:18:5
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:422:3)

【问题讨论】:

  • @Kalamarico 当您尝试关闭文件描述符 (fs.close(file)) 时,似乎发生了错误。这可能是因为您在上一行中异步执行fs.writeFile(file, output) 吗?可能值得尝试使用 fs.writeFileSync 或在 fs.writeFile / fs.close 上添加回调,看看它们中的任何一个是否在回调中抛出错误。
  • 尝试剂量工作
  • @Jason 我不是问题的主人,ryuu(他是主人)说你的提议没有成功

标签: javascript node.js angular


【解决方案1】:

fs.writeFile(...) 需要第三个(或第四个)参数,该参数是操作完成时要调用的回调函数。您应该提供回调函数或使用fs.writeFileSync(...)

请参阅node fs docs 了解更多信息。

【讨论】:

【解决方案2】:

试试这个。

 fs.readFile('readMe.txt', 'utf8', function (err, data) {
  fs.writeFile('writeMe.txt', data, function(err, result) {
     if(err) console.log('error', err);
   });
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2020-02-26
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 2021-05-02
    • 2020-04-16
    相关资源
    最近更新 更多