最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create file if it does not exist, then write logs to it - Stack Overflow

programmeradmin2浏览0评论

Trying to set up an environment that:

server.js: When the server is created, it will check if the a series of files exist: [api.log, error.log, access.log], if they do not yet exist, it will create them.

routes/api.js: I can use the file created at start up to, on api errors, log the error.

A lot of the advice revolves around fs.exists() which is now deprecated.

I am struggling to piece together the order of events, shall server.js check for files, act accordingly, then open a stream? Or must routes/api.js open the stream and write to it on every error?

I am using Node v5.0.0

Trying to set up an environment that:

server.js: When the server is created, it will check if the a series of files exist: [api.log, error.log, access.log], if they do not yet exist, it will create them.

routes/api.js: I can use the file created at start up to, on api errors, log the error.

A lot of the advice revolves around fs.exists() which is now deprecated.

I am struggling to piece together the order of events, shall server.js check for files, act accordingly, then open a stream? Or must routes/api.js open the stream and write to it on every error?

I am using Node v5.0.0

Share Improve this question asked Feb 23, 2016 at 1:08 speakspeak 5,4024 gold badges37 silver badges42 bronze badges 3
  • 1 What about fs.statSync? stackoverflow./a/4482701/4989460 – stdob-- Commented Feb 23, 2016 at 1:29
  • @stdob-- that is what I will be using for the check, any ideas about how I then use it? Is it as simple as referencing the file in a createWriteStream? Now that I can ensure the file will have been created? – speak Commented Feb 23, 2016 at 1:32
  • 1 Okay, I understand. Given the fact that the log files can write from different functions and at the same time, it will be better once to create an object of type "logger" - for example, winston [ github./winstonjs/… ]. – stdob-- Commented Feb 23, 2016 at 1:41
Add a ment  | 

1 Answer 1

Reset to default 7

You should never check for the existence of a file and then do something depending on whether the file does or doesn't exist. This is an anti-pattern: some other process might create or delete the file between when you check for the file's existence and when you then perform your next operation. (Even the *Sync methods—which are themselves anti-patterns—are vulnerable to this problem.)

Instead, you should just do whatever it is you need to do and handle errors appropriately.

In this case, you can let createWriteStream do the work for you by specifying flags. You probably want either:

  • 'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
  • 'a' - Open file for appending. The file is created if it does not exist.

Realistically, you should be using a logging library.

发布评论

评论列表(0)

  1. 暂无评论