gpt4 book ai didi

Node.js:追加到文件而不关闭句柄

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:07 24 4
gpt4 key购买 nike

我有博客,用 Node.js 编写,没有 Express...我想实现访问日志。

我想以 JSON 格式存储日志。有两个问题:首先,我不想打开文件句柄来访问日志文件,写入它,然后关闭它。我想在服务器启动时打开它,然后写入它并在关闭服务器时关闭它。是否可以?真的有效吗?

第二个问题:我想附加新日志而不是写入整个文件。日志采用数组的形式。有没有办法重写数组的右括号(]),在其后面添加日志对象并添加 ] 结束?

最佳答案

打开文件一次,写入多次

first, I don't want to open file handle to access log file, write to it, and then close it. I would like to just open it on server startup, and write to it and close it when I shut the server. Is it possible? Is it actually effective?

是的,这是可能且有效的。最适合您的解决方案是open WriteStream一次,然后使用其 .write() method 写入所有数据:

var log = fs.createWriteStream('./my.log', {
flags: 'a' // Open file for appending. The file is created if it does not exist.
})

log.write('Application started');

这比自己处理文件描述符安全得多,因为,as said in fs.write documentation :

Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

<小时/>

追加文件而不是重写它

I want to append new log instead of writing whole file

只需使用追加标志 a 而不是默认写入标志 w。了解更多see fs.open docs .

<小时/>

追加 JSON 数组

Logs are in form of an array. Is there any way rewrite closing bracket of the array (]) with, add log object behind it and add ] to end?

以这种格式存储日志是一个非常糟糕的主意。

日志记录的整个想法是能够快速将日志写入某个日志文件。您需要编写相当复杂的逻辑才能正确删除然后重新创建右括号 ]

当然有可能。但不这样做是一个更好的解决方案。

关于Node.js:追加到文件而不关闭句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com