Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active May 12, 2021 17:18
Show Gist options
  • Save ross-u/9eab7aa77bca58135202d8c96cb2d12f to your computer and use it in GitHub Desktop.
Save ross-u/9eab7aa77bca58135202d8c96cb2d12f to your computer and use it in GitHub Desktop.
M2 - Initlize npm and install a package - Exercise

Initlize npm and install a package - Exercise


img


Tasks

In a location of your choice on your local machine create a new directory called exercise-npm-init and initialize npm in the project so that you are able to install npm packages in the project.


First create the folder and the app.js file:

mkdir exercise-npm-init

cd exercise-npm-init

touch app.js

You will be writting your code in the app.js file


Initialize npm

Before installing any package, you first need to initialize npm in your project by running the below command.

This will create the manifest file package.json which enables you to use npm packages and track installed packages and their versions.


npm init -y

The -y flag when passed to npm init command tells the generator to use the defaults instead of asking questions.

It will simply generate an empty npm project manifest (package.json file) without going through an interactive process.


Install a npm package of your choice

Install a package from this list of npm packages, specifically the “weird” section.

Use the installed package in your app.js.

See its documentation to learn what it can do and how to use it.


Run the file with node

To run the app.js script in the NodeJS environment, you have to run the file from the terminal using node command and the name of the file:

node app.js

Bonus

In the same folder create another file me.js containing an object with the structure shown below, and then require it from the app.js and use it in there.

Remember to module.exports the me object in the me.js file, before require-ing it from app.js.

me.js
const me = {
  lName: "Your name",
  fName: "Your last name",
  catchPhrase: function () {
    console.log("Phrase you say often")
  },
  birthplace: "Your Birthplace"
}

// Here we have to export the above object using `module.exports`, before we can require it 
// from another file
module.exports = me;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment