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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With