【问题标题】:TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined in nodejsTypeError [ERR_INVALID_CALLBACK]:回调必须是函数。在nodejs中收到未定义
【发布时间】:2021-03-10 19:12:52
【问题描述】:

嗨,伙计们,我是 node js 的新手,我在尝试将我的文件附加到 node js 时遇到错误,不知道发生了什么问题,请尝试修复我的错误并告诉我该怎么办?

console.log("Starting app.js");

const fs = require('fs');
const os = require('os');
const notes = require('../notes-node/notes.js');

var user = os.userInfo();

fs.appendFile('message.txt', `Hello ${user.username}! You are ${notes.age}`)

console.log(user);

【问题讨论】:

    标签: node.js express nodemon


    【解决方案1】:

    你的fs.appendFile函数应该有一个回调函数作为第三个参数。

    语法:

    fs.appendFile( path, data[, options], callback )

    您的 JS 文件应如下更改:

    console.log("Starting app.js");
    
    const fs = require('fs');
    const os = require('os');
    const notes = require('../notes-node/notes.js');
    
    var user = os.userInfo();
    
    fs.appendFile("message.txt", `Hello ${user.username}! You are ${notes.age}`, (err) => { 
      if (err) { 
        console.log(err); 
      } 
    }); 
    
    console.log(user);
    

    有关fs.appendFile 的更多信息:https://nodejs.org/api/fs.html#fs_fs_appendfile_path_data_options_callback

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多