Node Cookbook - Fourth Edition by Bethany Griggs

Node Cookbook - Fourth Edition by Bethany Griggs

Author:Bethany Griggs
Language: eng
Format: mobi
Publisher: Packt Publishing Pvt. Ltd.
Published: 2020-11-23T16:00:00+00:00


Run the program, providing a task as an argument to the script:$ node tasks.js "Walk the dog."

Task: 0573rrpo3dpg = Walk the dog.

Now we can persist and list tasks in our LevelDB data store.

How it works…

The leveldown module is a binding for LevelDB written as a Node.js native module in C++. A Node.js native module provides an interface between the C++ library and JavaScript. The levelup module is a wrapper for the leveldown store that exposes a streaming interface to LevelDB data. Other stores can be used with levelup, as we'll touch on in the There's more… section.

When we call levelup(leveldown("./data")), a directory named data is created under our present working directory. This directory holds the data we store in LevelDB.

If a task has been supplied via command-line input, then our addTask() function will be executed. In this function, we create a key for the task. The key for the task starts with Task: and has a random hash appended to it. We use the Math.random() method to create a random hash.

The LevelDB put() method persists data into our LevelDB data store. We pass the put() method the key that we generated, and value, which is the task that was supplied via the command line. The last argument that we supply to the put() method is our callback function. Our callback function catches any errors and then proceeds to run the listTasks() function.

The listTasks() function calls db.createReadStream(), which returns a Readable Stream of the key-value pairs. The createReadStream() method, when supplied with no parameters, will return all key-value pairs stored in our LevelDB data store.

We register a data event handler on the stream returned from the createReadStream() method. Within the data event handler, as data is received, we output it to STDOUT using console.log().



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.