Getting started with my journal CLI

I decided the other day I would attempt to build out my CLI tool ideas for myself using NodeJS rather than Python or Rust.

From the short amount of time I started to look at the Node API and try some things out yesterday, I can tell this was likely the best choice for me at the moment.

I just built the simplest element of what I needed: Take a command and input when the file is run, and append to the 'storage' file.

Firstly to get the command and arguments in, I just used Node's built in argv. Rather than straight away rely on other packages, I wanted to get a feel for how it would work just using Node's own API first, then reach for more powerful and useful packages later on.

After initialising a new package.json with Yarn, I made an index.js file to build the basic elements of the utility.

// index.js

import {argv} from 'process';
import {appendFile} from 'fs';

const args = argv.slice(2); // argv also capture the node path and file path so I'm firstly dropping these.

const command = args[0]; // First element of the args array will be the command, I'm not doing any error handling yet, just assuming the command will always be giving for this basic test.

if (command === 'add'){
    const entryArr = args.slice(1); // Just removing the command so I have a clean array of the rest of the args.

    // argv returns all of the arguments as an array so I need to build the string which will be used as the entry.

    entryStr = entryArr.reduce((str, val) => str += `${val} `,'') // Using the reduce method is a really simple way to achive the required string. 
    // Arrays do have a toString() method however this adds a comma separator between each word which is not what I want. The desired result could also be achieved using 'forEach', 'map', or iterating over the array and incrementing the index. 

    // Finally I need to write/append the entry to the file. For now I'm just going to call the file 'log.txt'.
    appendFile('log.txt', entryStr, (err) => {
        if (err) throw err;
        console.log('Added entry to file')
    })
}

This is a really barebones example of getting started with taking arguments and appending them to a file. Eventually I inted to have a config file to enable chnaging of the file path and name of the log, along with various other 'user settings' just so I can read from a single configuration object and handle all of the various things from there.

What's next for this little project?

  • config file
  • adding the date and time to an entry (going to use day.js for this)
  • retrieving entries to view
  • reading from and writing to stdin and stdout for more flexibility of input/output

These are just a few small ideas I have for features I want, but I'll likely come up with more as I properly start to build it out.