0

我的节点 cli 脚本中有此代码

const dateTime = new Date();
const logFile = path.resolve(__dirname, `${dateTime.toLocaleDateString('it-IT')}.txt`);
const appLog = fs.createWriteStream(logFile, {flags: 'a+'});

console.log(chalk`{magenta.bold Log file created in ${appLog}}`);

//Logging events
            if( event.type === 'message' ){
                getInfo(eventID, (err, user) => {
                    if( err ){
                        appLog.write(err);
                        appLog.end();
                        return console.log(chalk.red.bold(err));
                    }
                    console.log(chalk`{yellow.bold New message:}\n${event.body}`); 
                    appLog.write(`${username}:`);
                    appLog.write(event.body);
                });
            }


我想要做的是在脚本启动时创建一个日志文件,然后在发生事件时将事件记录在新行上。问题是脚本将无法运行,并且由于文件不存在而出现错误。 Error: ENOENT: no such file or directory, open '/Users/dev/Desktop/node-fr/18/2/2021.txt' 如果文件不存在,我已经使用了a+应该创建文件的标志。我在做什么?

4

1 回答 1

1

改为使用标志“w”,这是默认标志。

const dateTime = new Date();
const logFile = path.resolve(__dirname, `./${dateTime.toLocaleDateString('it-IT')}.txt`);
const appLog = fs.createWriteStream(logFile, {flags: 'w'});

console.log(chalk`{magenta.bold Log file created in ${appLog}}`);

//Logging events
            if( event.type === 'message' ){
                getInfo(eventID, (err, user) => {
                    if( err ){
                        appLog.write(err);
                        appLog.end();
                        return console.log(chalk.red.bold(err));
                    }
                    console.log(chalk`{yellow.bold New message:}\n${event.body}`); 
                    appLog.write(`${username}:`);
                    appLog.write(event.body);
                });
            }
于 2021-02-18T17:28:22.737 回答