JavaScript

Create app options module using Object.freeze() method

In this tutorial we’ll make a separate JavaScript module to define some settings for our Duplicate File Finder app to help child and parent processes when they communicate with each other.

For example, when parent process send a message to child process to initialize the File Walker class:

//Parent to child message
child.send('start');

The child process reply after starting the walker:

//Child to parent message
process.send('started');

For the ease of communication we can create an ‘options.js‘ module as shown below:

//options.js
module.exports = Object.freeze({
 STARTED:1,
 STOPPED:2,
 PAUSED :3,
 RESUMED:4,
 DONE   :5,
 START  :6,
 STOP   :7,
 PAUSE  :8,
 RESUME :9,
 RESET  :10,
 FILE   :11,
 DIR    :12,
 UNKNOW :13,
 ERROR  :14,
 DEBUG  :15,
 WEBVIEW:16
});

JavaScript’s Object.freeze() function can prevent an object’s state from changing. Any attempt to change it will result in an error:

TypeError: Cannot assign to read only property...

The freeze() function prevents properties to be added, modified, or removed. An object in this state is considered immutable.

For more information visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze.

The following example demonstrates the usage of options.js module:

//parent
...
var OPT = require ('./options.js');
child.send(OPT.START);
...

//child
...
var OPT = require ('./options.js');
process.send(OPT.STARTED);
...

In next tutorials, we’ll create:

  1. a dynamic and resizable table to show duplicate files found after the completion of path scanning.
  2. add more features to our pause and resumable file walker class, such as:
    1. obtaining the hash of a file
    2. return the content of a file
Advertisement:
Advertisement: