简体   繁体   English

如何将数据记录到新文件中?

[英]how to log data into a new file?

I'm a beginner to node.js, started to learn just a few days ago.我是 node.js 的初学者,几天前才开始学习。 i'm trying to log the listener's data into a new file by using fs.appendFile , but no matter how many times i try to change the code, it keeps giving me an ERR-INVALID-CALLBACK .我正在尝试使用fs.appendFile将侦听器的数据记录到一个新文件中,但无论我尝试更改代码多少次,它都会给我一个ERR-INVALID-CALLBACK

const Logger = require('./logger_demo')
const logger = new Logger
const fs = require('fs')
logger.on('message', data => console.log('Called Listener: ', data))
fs.appendFile('./log_demo.js', 'message', (err) => {
  if (err) throw err
  console.log('File has been appended!')
})

fs.appendFile(logger.log('Hello World!'))

I'm not sure what I'm doing wrong, any idea how to solve this?我不确定我做错了什么,知道如何解决这个问题吗?

I think the issue may be here:我认为问题可能出在这里:

const logger = new Logger

Should it be this?应该是这个吗?

const logger = new Logger()

Additionally, you need to give a file-path to fs.appendFile :此外,您需要为fs.appendFile提供一个文件路径:

fs.appendFile("log.txt", logger.log('Hello World!'))

But I think you meant to do this:但我认为你打算这样做:

logger.log('Hello World!')
fs.appendFile(logger.log('Hello World!'))

This line is your problem you are calling fs.appendFile with wrong parameters此行是您使用错误参数调用fs.appendFile的问题

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

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