About Node.js

Here are my notes about Node.js that I just started learning from this month (Jan 2021).

What is Node.js

The grammar is the same as Javascript but unlike JS on the client-side (browser). It used on the Server-side so it can read/write files…etc. Both JS and node.js share common methods such as toUpperCase()…but they also have their own methods such as the window and document function of JS in the browser and the global and process function of Node in the Server.

Execute node.js Script

After installed the node.js, create a js file with console.log(“AnythingHere”), open the cmd/terminal, and type “node YourFileName.js”.

Write file with node.js

Refer to the documentation, first, require the fs module. Then use

const fs = require('fs');
fs.writeFileSync("temp.txt","hello world --testing nodejs");
nodejs.org Documentation

Import your own file

Create 2 js files, one for export, one import. In the import file, use require() method to catch data from the export file. In the export file, use module.exports to output data.

“npm init” to use npm Modules

In the target folder, type “npm init” in the command line allow you to create a single configuration file that we can use to manage all of the dependencies from the NPM Web site that we want to install.

I think npm is similar to the pip for Python. It let us use the knowledge/written code shared on the internet.

Play with Argument from command line

Use process.argv to use the argument input in the command line.

node filename.js arg

Because the process.argv will return a list. This means we can use [2] to play with it.

“yargs” npm package

yargs npm let us easily paly with arg. We can use “yargs.command” to create our app. See the example below.

First, of course, import/require the yargs package and put it into a variable. Then create a command object. In the command line. Just like the process.argv example above, type this in the terminal/cmd:

node filename.js --help

node filename.js YourCommand --key=value --key2=value2

~ –help can allow you to see your command name with the description.

Leave a Comment

Your email address will not be published. Required fields are marked *

Follow by Email