How it works...

Both fs and path are core modules, so there's no need to install these dependencies.

The path.join method is a useful utility that normalizes paths across platforms, since Windows uses back slashes () whilst others use forward slashes (/) to denote path segments.

We use this three times, all with the cwd reference which we obtain by calling process.cwd() to fetch the current working directory.

The fs.readFileSync method will synchronously read the entire file into the process memory.

This means that any queued logic is blocked until the entire file is read, thus ruining any capacity for concurrent operations (such as serving web requests).

That's why synchronous operations are usually explicit in Node Core (for instance, the Sync in readFileSync).

For our current purposes, it doesn't matter, since we're interested only in processing a single set of sequential actions in a series.

So we read the contents of file.dat using fs.readFileSync and assign the resulting buffer to bytes.

Next we remove the zero-bytes, using a filter method. By default, fs.readFileSync returns a Buffer object, which is a container for the binary data. Buffer objects inherit from native UInt8Array (part of the ECMAScript 6 specification), which in turn inherits from the native JavaScript Array constructor.

This means we can call functional methods such as filter (or map, or reduce) on Buffer objects!

The filter method is passed a predicate function, which simply returns the value passed into it. If the value is 0, the byte will be removed from the bytes array because the number 0 is coerced to false in Boolean checking contexts.

The filter bytes are assigned to clean, which is then written synchronously to a file named clean.dat, using fs.writeFileSync. Again, because the operation is synchronous nothing else can happen until the write is complete.

Finally, we use fs.appendFileSync to record the date and amount of bytes removed to a log.txt file. If the log.txt file doesn't exist, it will automatically be created and written to.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset