NPM packages Flashcards

1
Q

What is the difference between dependencies, devDependencies and global installs?

A

devDependencies are used when we are developing the project, while dependencies are used within the application code.

In order to save a devDependency we need to
npm install package-name –save-dev

Global installs are available anywhere on our machine. A package should be installed globally, if it provides an executable command that can be run from the CLI.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does nodemon package do?

A

Nodemon is a package, that we use to automatically restart server upon saving changes in the code.

It should be installed in the –save-dev
devDependencies.

nodemon index.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is slugify?

A

Slugify is a package that can help us to make more readable urls out of names.

Slug - is the last part of the url that contains the string that identifies the resource the website is displaying.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the meaning of semantic version notation of versions of npm packages?

A

Usually, npm package version number is expressed with these three numbers: “^1.18.11”;
The first number, is the major version (huge new release, which can have breaking changes),
second number is the minor version (introduces new features, but not breaking changes - always are backward compatible)
third one is patch version (only intended to fix bugs).

  • will accept all of the versions (is not safe, because, the versions might contain breaking changes)
    ^ will accept patch and minor releases
    ~ will accept only patch releases (is safer)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can we update and delete packages in NPM?

A
  1. Check if there are any outdated packages (should give us a table with all packages that are outdated):
    npm outdated
  2. npm update slugify
    (cares about ^ or ~).

We can install an older version of a package by:
npm install slugify@1.0.0

To delete a package, we need to
npm uninstall slugify

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the procedure to install packages in your project?

A
  1. Node package manager automatically comes with installment of node.js.
  2. A good habit when working on a new project that will be using packages is to
    npm init
    in the project directory. This will create a package.json file that tracks our devDependencies.
  3. To install a package we need to type in vs code terminal
    npm install
    command. --save-dev` (and save the dependencies in the package.json file.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the procedure to install babelJS?

A

To install babel inside our project directory we need to have a node environment.

  1. init the project package.json with
    npm init
    command.
  2. install packages:
    npm install @babel/core @babel/cli --save-dev
    babel cli - command line interface, to use babel in cmd.
  3. Install babel preset:
    npm install @babel/preset-env
  4. Create a .babelrc file and store the presets in an object. Then, when we run babel, the program will know which preset to run, because it knows about .babelrc file.

{
“presets”: [“@babel/preset-env”]
}

How can we run babelJS?

In order to run babel compiler we need to run a command in CLI.

In the command, we need to:

  1. Locate the babel bin in node_modules folder.
  2. select the file that we want to compile
  3. specify the output destination and name of the file.

node_modules/.bin/babel ./scripts/before.js -o ./scripts/after.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Installation of packages used in projects.

A

Whenever we send the project to another developer or upload to github repository, we do not include node_modules folder.
node_modules is the location of all packages scripts and simply that is a lot of code.
However all of the dependencies are stored in package.json file. When we upload a project, we just need to upload the package.json file.

Then, when the project is downloaded, simple command npm install will install all the dependencies located in package.json.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the purpose of using NPM Scripts and Watching files?

A

NPM Scripts allow us to automate he process of bundling/compiling files.
In our project directory we could have a src and dist folders

Mode LastWriteTime Length Name
—- ————- —— —-
d—– 9/22/2020 11:14 AM dist
d—– 9/22/2020 11:02 AM node_modules
d—– 9/22/2020 11:14 AM src
-a—- 9/22/2020 10:42 AM 42 .babelrc
-a—- 9/22/2020 10:49 AM 123351 package-lock.json
-a—- 9/22/2020 11:21 AM 370 package.json

src, being the folder for all scripts with modern features.
dist, folder thats being uploaded on the server (with index.html etc).

In our package.json, we could create a script
“scripts”: {
“babel”: “node_modules/.bin/babel ./src/index.js (-w) -o ./dist/assets/bundle.js”
}

This will allow us to run command

npm run babel
. And bundle the js file. We could additionally add a -w modifier, that will watch any changes in the source code in index.js and automatically comile it into bundle.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Installation of webpack

A

How to set up a webpack.config.js file?

const path = require('path');
// require path module located in node_modules

module.exports = {
entry: ‘./src/index.js’,
output: {
path: path.resolve(__dirname, ‘dist/assets’),
filename: ‘bundle.js’
}
};

npm install webpack webpack-cli --save-dev
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you set up webpack dev server?

A
  1. Install package
    npm install webpack-dev-server
  2. add configuration to webpack.config.js file
    devServer: {
    contentBase: path.resolve(__dirname, ‘dist’),
    publicPath: ‘/assets/’
    }
  3. add a script to build run dev server.
    “dev-server”: “webpack-dev-server –mode development”
    (–mode production to run for producion).

How do you set up CSS loaders?
1. Install
npm install css-loader style-loader –save-dev

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is morgan?

A

Morgan is a logging middleware. It logs HTTP requests to the console. It used to be a built in express.
In order to include morgan in our express app, we need to install it by npm.
and
app.use(morgan(‘dev’))
morgan(‘dev’) returns a middleware function that the app uses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of dotenv package?

A

dotenv is a standard package to set up environmental variables (config.env). It reads the variables from the file and saves them as environment variables, so they are accessible in process.env.nameOfVariable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you set up prettier together with ESLint extensions?

A

Bunch of dependencies:
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-config-airbnb eslint-plugin-node eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react –save-dev

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is mongoose?

A

Mongoose is an Object Data Modeling (ODM) Library for MongoDB and Node.js, providing a higher level of abstraction.

  • schemas to model data and relationshipts
  • easy data validation
  • simple query api
  • middleware
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is validator.js

A

Validator is a library for string validators and sanitizers

17
Q

What is the package that can help with hashing and protecting data in the node app?

A

npm install bcryptjs

// 12, is  a parameter, how CPU intensive will be the process of encrypting that password.
bcrypt.hash(this.password, 12) 
function comes with both synchronous and asynchronous versions. Of course, usually we want to use the asynchronous version.
Because of the fact that bcrypt.hash will return a promise, we need to await that promise in our mongoose pre save hook.

In order to compare for example two passwords, we should create an instance method on the Schema.
This method should
return await bcrypt.compare(password[string], encryptedPassword[hash]),
This function is asynchronous, but will return either true or false.

18
Q

What is jsonwebtoken package and how does it work?

A

jsonwebtoken package is an interface that allows us to use jsonwebtokens in our authorization mechanisms.

The package has 2 major methods, that have to do with how jwt work.

jwt. sign(payload, secretOrPrivateKey, [options, callback])
jwt. verify(token, process.env.JWT_SECRET)

JWT_SECRET is a variable that should be defined in .env file. The string for better encryption should be at least 32 chars long, of course, it should be unique.

19
Q

What is a node package, that allows us to send emails?

A

npm install nodemailer

In order to send emails with node mailer,
in the sendEmail function we need to pass an options object and follow these steps:

  1. Create a transporter (a service that will actually send an email)
  const transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
      user: process.env.EMAIL_USERNAME,
      pass: process.env.EMAIL_PASSWORD
    }
    // In Gmail account, active "Less secure app option"
  });
// A good service for testing development emails is mailtrap.io
2. Define mail options
  const mailOptions = {
    from: 'Jonas Schmedtmann ',
    to: options.email,
    subject: options.subject,
    text: options.message
    // html:
  };
  1. Actually send the email

await transporter.sendMail(mailOptions);

20
Q

What is the rate limiting package that we can implement with the npm?

A

Rate limiter, prevents the same ip from making to many requests to our api. It helps us prevent DDOS and bruteforce attacks.
It, basically counts the number of requests from the same API and blocks it if the amount of requests exceeds the limit.

to install rate limiter
npm install express-rate-limit

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
  max: 100, //maximum no of calls in the timewindow
  windowMs: 60 * 60 * 1000, //timewindow in ms
  message: 'Too many requests from this IP, please try again in an hour' 
});
app.use('/api', limiter); //we mount the limiter on the api route.
21
Q

What is helmet?

A

Helmet is a npm package, that will help us set some important HTTP security headers. It’s best to use this package early in the middleware stack, so the headers are set early.

Headers:
X-DNS-Prefetch-Control
Strict-Transport-Secuirty
X-Download-Options
X-XSS-Protection
const helmet = require('helmet');
app.use(helmet());
22
Q

What are the npm, express packages that can help us with data sanitization?

A

npm install express-mongo-sanitize
npm install xss-clean

app.use(mongoSanitize());
What mongoSanitize does is to look at the request body, request queryString and request.params and filter out all $ signs and dots.

app.use(xss());
xss will clean any user input from any malicious html code with js code attached to it.

23
Q

What is HPP?

A
Express middleware to protect against HTTP Parameter Pollution attacks. 
// GET /search?firstname=John&firstname=John
req.query.firstname
//=>["John", "John"]
Express poplates HTTP requests parameters with same name in an array. Attackers can intentionally pollute request parameters to exploit this mechanism
const hpp = require('hpp');
app.use(
  hpp({
    whitelist: [
      'duration',
      'ratingsQuantity',
      'ratingsAverage',
      'maxGroupSize',
      'difficulty',
      'price'
    ]
  })
);

as a option we can pass whitelist Array, which lists all the whitelisted parameters.

24
Q

How to setup global variable in postman (postman is not an npm package, but I dont have where to put)

A

pm.globals.set(“jwt”, pm.response.json().token);

25
Q

What is crypto module?

A

crypto is a built in node module. It provides simple random bytes, as well as hashing functions, that can be used for instance in creation of forgotPassword tokens..

const resetToken = crypto.randomBytes(32).toString(‘hex’);

this.passwordResetToken = crypto
.createHash(‘sha256’)
.update(resetToken)
.digest(‘hex’);

26
Q

What is cookie parser?

A

Cookie parser is similar to JSON parser.
It allows us to parse cookies from the request.

npm install cookie-parser
const cookieParser = require('cookie-parser');

app.use(cookieParser());

Then on the req object, we will for example have access to the cookies.
req.cookies

27
Q

What is multer package?

A

Multer is a package that helps to deal with multi part form data.
It works as a middleware, that allows us to save upload photos and save them in the filesystem. In order to use the middleware, we need to invoke it in the route.
like: upload = multer({storage: multerStorage,
fileFilter: multerFilter}),

then, use it in the middleware stack for a specific route.
upload.single(‘photo’) (pass the name of the field that will hold value)

We need to configure multerStorage and fileFilter middleware functions.
// multer storage defines the filepath and filename of the uploaded file

const multerStorage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, ‘public/img/users’);
},
filename: (req, file, callback) => {
const ext = file.mimetype.split(‘/’)[1];
callback(
null,
user-${req.user.name.split(' ')[0].toLowerCase()}-${Date.now()}.${ext}
);
}
});
// we can also store the image in the memory like:
const multerStorage = multer.memoryStorage();
Then it is accessible in the req.file.buffer

// multer filter checks if the file is valid and returns true or an error
const multerFilter = (req, file, callback) => {
  if (file.mimetype.startsWith('image')) {
    callback(null, true);
  } else {
    callback(
      new AppError('Not an image. Please upload only images.', 400),
      false
    );
  }
};
28
Q

What package can we use to resize images?

A

npm install sharp
Sharp is an image processing library that we can with node js.
We can write yet another middleware function that we need to use in the middleware stack.

exports.resizeUserPhoto = (req, res, next) => {
if (!req.file) return next();

req.file.filename = user-${req.user.name .split(' ')[0] .toLowerCase()}-${Date.now()}.jpeg;

  sharp(req.file.buffer)
    .resize(500, 500)
    .toFormat('jpeg')
    .jpeg({ quality: 90 })
    .toFile(`public/img/users/${req.file.filename}`);

next();
};

29
Q

How can you configure jimp and uuid?

A

jiimp is an image processing library, while uuid is a library that ensures the uniqueness of names that are uploaded.

  req.body.photo = `${uuid.v4()}.${extension}`;
  const photo = await jimp.read(req.file.buffer);
  await photo.resize(800, jimp.AUTO);
  await photo.write(`./public/uploads/${req.body.photo}`);
30
Q

What is a mongodb error handling library?

A

const mongodbErrorHandler = require(‘mongoose-mongodb-errors’);

we can add this plugin in userSchema like:

userSchema.plugin(mongodbErrorHandler);

31
Q

How does express-validator work?

A
const {
  body,
  validationResult,
  check,
} = require('express-validator');

In order to sanitize the form submission, we can add middleware to the middleware stack

[body(‘email’).notEmpty().withMessage(‘You must supply an email’).isEmail().withMessage(‘Email has to have correct format!’).normalizeEmail(),
body(‘name’).notEmpty().withMessage(‘You must supply a name’).trim().escape(),
body(‘password’).notEmpty().withMessage(‘Password cannot be empty!’),
body(‘password-confirm’).notEmpty().withMessage(‘Confirm password cannot be empty!’).equals(check(‘password’)).withMessage(‘Passwords do not match!’)]

Then in the middleware, we can check for errors during validation and sanitization

const errors = validationResult(req);
if (!errors.isEmpty()){
const sth = errors.array().map(err=>err.msg);
// logic
}
32
Q

What does juice library do?

A

Juice is a handy library that will inline the css that we have attached to our email, so it works better in some email clients.

const juice = require(“juice”);

  const html = pug.renderFile(
    `${\_\_dirname}/../views/email/${filename}.pug`,
    options
  );
  const inlined = juice(html);