0

A call to writeFileSync is producing a 0 bytes file at random.

The aim is to write a json to a file, then re-write it every time the json changes. And also load the json on startup. But the file keeps becoming 0 bytes long, most of the time it works then after a few days it becomes 0 bytes.

Code: LiveScript https://github.com/audreyt/ethercalc/blob/master/src/db.ls Or converted to JavaScript https://github.com/audreyt/ethercalc/blob/master/db.js

   try
      db.DB = JSON.parse do
        require \fs .readFileSync "#dataDir/dump.json" \utf8
      console.log "==> Restored previous session from JSON file"
      db.DB = {} if db.DB is true
    Commands =
      bgsave: (cb) ->
        fs.writeFileSync do
          "#dataDir/dump.json"
          JSON.stringify db.DB,,2
          \utf8
        cb?!

With logging etc:

if fs.existsSync "#dataDir/dump.json" #check file exists - throws exception if exists and read fails
  #console.log "==> Found previous JSON file"
  try      
    db.DB = JSON.parse do
      require \fs .readFileSync "#dataDir/dump.json" \utf8
    console.log "==> Restored previous session from JSON file"
    db.DB = {} if db.DB is true
  catch 
    console.log "dump file locked, exit process"
    process.exit! 
else
  console.log "No existing dump file - #dataDir/dump.json "
Commands =
  bgsave: (cb) ->
    fs.writeFileSync do
      "#dataDir/dump.json"
      JSON.stringify db.DB,,2
      \utf8
    cb?!

Suggestion on how to debug or re-structure much appreciated.

Notes: - Workaround - When I added an auto restart every 24 hours it fixed the problem.
- When it becomes 0 bytes, the code prints "dump file locked, exit process" - the code is running on an openshift server - looks to becomes 0 bytes when the server is auto restarted - not a manual restart, but when the server decides to trigger a restart

eddyparkinson
  • 3,680
  • 4
  • 26
  • 52
  • Please tag your question with the appropriate syntax tag since this is not apparently regular Javascript. – jfriend00 Oct 31 '16 at 01:55
  • @jfriend00 js version https://github.com/audreyt/ethercalc/blob/master/db.js - sorry - it is livescript which is a fork of coffeescript – eddyparkinson Oct 31 '16 at 02:46
  • 1
    I'd rather say "LiveScript is a fork of Coco and an indirect descendant of CoffeeScript, with which it has much compatibility. " – Ehvince Nov 02 '16 at 12:43
  • are you sure you don't have any concurrent writes or stuff like that? – Ven Jan 11 '17 at 09:46
  • also `db.DB = {} if db.DB is true` is `db.DB &&= {}` – Ven Jan 11 '17 at 09:47
  • @Ven thanks for the thoughts. writeFileSync is synchronous - writeFileSync is always used to write - by Tom: "Oddly enough "Synchronously" means "using the same clock" so when two instructions are synchronous they use the same clock and must happen one after the other. - http://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean – eddyparkinson Jan 12 '17 at 01:00

0 Answers0