A method of persisting various JavaScript objects and arrays

Usage no npm install needed!

<script type="module">
  import contentPersistence from '';



Node module to persist various JavaScript objects and arrays into flat files

const ContentPersistence = require('content-persistence').contentPersistence;

var object = new ContentPersistence('.', 'chaiQueue', function(err, content) {
    let test = [{alpha: 1}, {beta: 2}, {gamma: 3}, {delta: 'four'}];


  • constructor(path, filename, reviver[optional], callback) Reads from disk the given file by path and filename and pass its content to the function provided as callback. If file does not exist it will retrieve null. If reviver function is provided, it will be used when executing JSON.parse over the content of the file.
  • set(content, callback) Writes to disk with the given content. It will replace any previous content if the file already exists.
  • clear(callback) Empties the content of the given file. It leaves file content as {}.


  • content is expected to be always a JSON object. In the same way, read operations will retrieve files content in JSON format through the aforementioned JSON.parse.
  • When closing the library using close(), the system will wait for the write queue to be flushed to disk. During this time no new persistent writes can be made. If the write queue can not be flushed to disk an EQUEUETO error will be returned via the close() callback function. The persistence storage can be activated again (after a call to close) using the open() function.

Persistence singleton object contains the following methods:

  • readDir(directoryPath, callback)
  • removeDir(directoryPath, callback)
  • validFileName(filename)
  • validKey(directoryPath, file, callback)
  • read(directoryPath, file, callback)
    • This function can retrieve the following errors (of the format: { code: ..., message: ..., file:..., exception:.... }):
      • EPJSON: File has a content which cannot be parsed to JSON.
  • write(directoryPath, file, content, callback)
    • This function can retrieve the following errors:
      • ECLOSED: The persistence library has been closed and no writes will be allowed until it has been opened again.
      • EEMPTYJSON: An empty content has been passed.
      • EWJSON: Raised when either fs.writeFile or JSON.stringify fails.
  • remove(directoryPath, file, callback)
  • open()
  • close()
    • This function can produce the following error:
      • EQUEUETO: Timeout waiting for queue to be flushed