简体   繁体   English

TypeError [ERR_INVALID_CALLBACK]: 回调必须是一个函数

[英]TypeError [ERR_INVALID_CALLBACK]: Callback must be a function

I wanted to make a script to add a new rule to angular webpack app, as below.Some times the code executes partially, some times it give erorr.我想编写一个脚本来向 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)

fs.writeFile(...) requires a third (or fourth) parameter which is a callback function to be invoked when the operation completes. fs.writeFile(...)需要第三个(或第四个)参数,这是在操作完成时调用的回调函数。 You should either provide a callback function or use fs.writeFileSync(...)您应该提供回调函数或使用fs.writeFileSync(...)

See node fs docs for more info.有关更多信息,请参阅节点 fs 文档

Try this.尝试这个。

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

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

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