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
1 Answer
Reset to default 7You 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.