我的Node.js程序-这是一个普通的命令行程序,基本上不会执行任何操作异常,没有系统特定或异步的操作或类似的操作-需要不时将消息写入文件,然后它将被^ C中断,它需要文件的内容仍然存在.
My Node.js program - which is an ordinary command line program that by and large doesn't do anything operationally unusual, nothing system-specific or asynchronous or anything like that - needs to write messages to a file from time to time, and then it will be interrupted with ^C and it needs the contents of the file to still be there.
我尝试使用fs.createWriteStream,但是最后只是一个0字节的文件. (如果程序通过运行主文件的结尾而结束,则该文件中确实包含文本,但这不是我遇到的情况.)
I've tried using fs.createWriteStream but that just ends up with a 0-byte file. (The file does contain text if the program ends by running off the end of the main file, but that's not the scenario I have.)
我尝试使用winston,但是最终根本不创建文件. (如果程序通过运行主文件的结尾而结束,则该文件中确实包含文本,但这不是我遇到的情况.)
I've tried using winston but that ends up not creating the file at all. (The file does contain text if the program ends by running off the end of the main file, but that's not the scenario I have.)
并且fs.writeFile在您具有所有要预先编写的文本的情况下可以完美地工作,但是似乎不支持一次添加一行.
And fs.writeFile works perfectly when you have all the text you want to write up front, but doesn't seem to support appending a line at a time.
推荐的方法是什么?
我尝试过的特定代码:
var fs = require('fs') var log = fs.createWriteStream('test.log') for (var i = 0; i < 1000000; i++) { console.log(i) log.write(i + '\n') }运行几秒钟,按^ C,留下一个0字节的文件.
Run for a few seconds, hit ^C, leaves a 0-byte file.
推荐答案结果证明Node提供了一个较低级别的文件I/O API,看来工作正常!
Turns out Node provides a lower level file I/O API that seems to work fine!
var fs = require('fs') var log = fs.openSync('test.log', 'w') for (var i = 0; i < 100000; i++) { console.log(i) fs.writeSync(log, i + '\n') }更多推荐
如何增量写入文本文件并刷新输出
发布评论