Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file if it does not exist, then write logs to it

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

like image 474
speak Avatar asked Mar 13 '23 05:03

speak


1 Answers

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.

like image 189
josh3736 Avatar answered Mar 16 '23 06:03

josh3736