bcherny
bcherny

Reputation: 3172

filesystem read/write: Is this a race condition?

import {appendFile, readFile} from 'fs'

// Read data from an Apache server's access log
readFile(
  '/var/log/apache2/access_log',
  {encoding: 'utf8'},
  (error, data) => {
    if (error) {
      console.error('error reading!', error)
      return
    }
    console.info('success reading!', data)
  }
)

// Concurrently, write data to the same access log
appendFile(
  '/var/log/apache2/access_log',
  'New access log entry',
  error => {
    if (error) {
      console.error('error writing!', error)
    }
  })

Is it guaranteed that the read will complete before the appendFile writes to the filesystem, or is it possible that my data might get appended before the readFile completes, so that readFile returns my newly-appended data?

Upvotes: 0

Views: 243

Answers (1)

bcherny
bcherny

Reputation: 3172

Trying this out with a quick test, it really is unstable:

https://gist.github.com/bcherny/029473f21833a73126d2e1dce53f2a6a

Upvotes: 1

Related Questions