ITKarma picture

Good day, friends!

I continue to publish translations of this Node.js tutorial .

Other parts:
Part 1
Part 2
Part 3

Getting user input into Node.js


How to make a Node.js program interactive?

To do this, version 7 of Node.js introduces the readline module: it serves to receive data from a read stream such as CDMY0CDMY is the command line at runtime of a Node.js program.

const readline=require('readline').createInterface({ input: process.stdin, output: process.stdout }) readline.question(`What is your name?`, name => { console.log(`Hi ${name}!`) readline.close() }) 

In this code, the user name is requested, after the user has typed and pressed CDMY1CDMY, a greeting is displayed.

The CDMY2CDMY method displays the first parameter (question) to the console and waits for a user response. When CDMY3CDMY is pressed, the callback function is executed.

In this callback, we close the CDMY4CDMY interface.

CDMY5CDMY also contains other methods that you can read about in the documentation.

If you need to request a password, it is better not to return it explicitly, but to use CDMY6CDMY characters.

One way to do this is to use the readline-sync package, which is easy to understand and easy to use. at the construction site.

A more complete and abstract solution is provided by the Inquirer.js package.

Install it using CDMY7CDMY and use it as follows:

const inquirer=require('inquirer') const questions=[ { type: 'input', name: 'name', message: `What's your name?` } ] inquirer.prompt(questions).then(answers => { console.log(`Hi ${answers['name']}!`) }) 

Inquirer.js allows you to do many interesting things, for example, offer multiple choices, provide radio buttons, request confirmation of action, etc.

It is better known as an alternative to embedded solutions, but if you plan to take user interaction to a new level, Inquirer.js is the optimal solution.

Extending the functionality of a Node.js file using export


Node.js has an integrated modular system.

Node.js file can import functionality from other Node.js files.

When you want to import something you use CDMY8CDMY
to import the functionality exported in the CDMY9CDMY file located in the current directory.

In this file, the functionality must be exported before it can be imported into another file.

Any other object or variable defined in the file is private (private) by default and cannot be used in other files.

This is what the CDMY10CDMY interface allows us to do, provided by the modular system .

When you assign an object or function as a new property of an CDMY11CDMY object, you export them, and then they can be imported elsewhere in the application or in another application.

There are two ways to do this.

The first way is to assign the value CDMY12CDMY, which is the default object provided by the modular system. This method allows you to export only this object:

const car={ brand: 'Ford', model: 'Fiesta' } module.exports=car//в другом файле const car=require('./car') 

The second way is to add the exported object as a property of the CDMY13CDMY object. This method allows you to export many objects, functions, or data:

const car={ brand: 'Ford', model: 'Fiesta' } exports.car=car 

or so

exports.car={ brand: 'Ford', model: 'Fiesta' } 

To use this object in another file, you must make a link to import:

const items=require('./items') items.car 

or

const car=require('./items').car 

What is the difference between CDMY14CDMY and CDMY15CDMY?

The first exports the object referenced, the second - the property of the object.

Introduction to the npm Package Manager


Introduction to npm

CDMY16CDMY is a standard Node.js package manager.

In January 2017, npm had over 350,000 packages, which made it the largest repository of code in one programming language on Earth, and you can be sure that there are packages for solving almost any task.

It all started with loading and managing dependencies in Node.js, but soon this tool became actively used in developing the client part of applications.

CDMY17CDMY does a few things.

An alternative to npm is yarn .

Download

CDMY18CDMY manages project dependency loading.

If the CDMY19CDMY file exists in the project by starting CDMY20CDMY, everything that the project requires is installed in the CDMY21CDMY directory, which is created if not present.

A specific package can be installed using CDMY22CDMY.

Often the installation of a package is accompanied by flags:

  • --save - install the package and add a record about it to the dependencies section of the CDMY23CDMY file
  • --save-dev - install the package and add a record about it to the devDependencies section of the CDMY24CDMY file

The difference mainly lies in the fact that devDependencies is used for development purposes, for example, for testing, and dependencies is used in production (when building a project).

Update packages

The upgrade is easy with CDMY25CDMY.

CDMY26CDMY will check all packages for new versions that meet the established restrictions.

You can also upgrade only a specific package: CDMY27CDMY.

Versioning

In addition to the standard download, npm supports versioning, so you can define any specific version of the package, or request a newer or older version.

You will often find that one library is only compatible with a certain (major) version of another library.

And also with bugs of the latest releases that have not been fixed for a long time.

Versioning also contributes to team development, as each team member knows which version to use before updating the CDMY28CDMY file.

Versioning helps in all of these cases, and CDMY29CDMY follows accepted standards in this regard.

Complete tasks

CDMY30CDMY supports a format for defining commands executed in a terminal using CDMY31CDMY.

For example:

{ "scripts": { "start-dev": "node lib/server-development", "start": "node lib/server-production" }, } 

A common practice is to use this feature to start Webpack:
{ "scripts": { "watch": "webpack --watch --progress --colors --config webpack.conf.js", "dev": "webpack --progress --colors --config webpack.conf.js", "prod": "NODE_ENV=production webpack -p --config webpack.conf.js" }, } 

This allows you to do so instead of a set of long commands that are easy to forget or that are easy to make when typing:

npm run watch npm run dev npm run prod 


Where does npm install packages?


When installing packages using CDMY32CDMY, you can choose two types of installation:

  • local
  • global

By default, when you enter CDMY33CDMY, for example:

npm install lodash 

the package is installed in the CDMY34CDMY folder in the current directory.

After installation, CDMY35CDMY adds an entry for CDMY36CDMY to the CDMY37CDMY section of the CDMY38CDMY file in the current directory.

For global installation, use the CDMY39CDMY flag:

npm install -g lodash 

In a global installation, the package is not installed in the current directory, but in the global one.

But where exactly?

To determine this, run the CDMY40CDMY command.

On macOS or Linux, the directory may be CDMY41CDMY. On Windows, CDMY42CDMY.

When using CDMY43CDMY for version control Node.js, this directory may be different.

How to use installed packages?


How to use the package installed in the CDMY44CDMY folder or globally.

Say you installed CDMY45CDMY, a popular JavaScript helper library, using CDMY46CDMY.

This command installs CDMY47CDMY in the local directory CDMY48CDMY.

To use the program, you must import the package using CDMY49CDMY:

const _=require('lodash') 

What if the package is executable (file)?

In this case, the executable will be placed in the CDMY50CDMY directory.

This can be easily demonstrated using the cowsay library.

This package provides a command line program, during which the cow (and other animals) “says” something.

When installing a package using CDMY51CDMY, the package itself and several of its dependencies will be installed:

ITKarma picture

The CDMY52CDMY folder is hidden and contains symbolic links to cowsay binary data:

ITKarma picture

How to fulfill them?

Of course, you can type CDMY53CDMY and everything will work, but npx included in npm (since version 5.2) is the best option. You just run CDMY54CDMY and npx will locate the file automatically:

ITKarma picture
The cow says, "Take me out of here."

Package.json Guide


When working with JavaScript, when interacting with a JavaScript project, Node.js or the client part of the application, you will surely come across the CDMY55CDMY file.

What it is? What should you not know about? And what can you do with it?

CDMY56CDMY is a kind of project manifesto. He can do many things that are completely unconnected. It, for example, can be the main file for the settings of the tools used. It also stores the names and versions of all installed packages (this information is used by CDMY57CDMY and CDMY58CDMY).

File structure

Here is an example of CDMY59CDMY:

{} 

As you can see, it is empty. The content of CDMY60CDMY is not subject to any requirements. The only requirement is its format (JSON), otherwise, programs will not be able to access it.

If you create a Node.js package that you plan to distribute through CDMY61CDMY, the situation changes dramatically, and you need to add properties that will help other people use the package. We will review this later.

Here is another example of CDMY62CDMY:

"name": "test-project" 

Here we defined the name of the package or application located in the same directory as CDMY63CDMY.

Here is an example of the more complex CDMY64CDMY, borrowed from the Vue.js application:

{ "name": "test-project", "version": "1.0.0", "description": "A Vue.js project", "main": "src/main.js", "private": true, "scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", "unit": "jest --config test/unit/jest.conf.js --coverage", "test": "npm run unit", "lint": "eslint --ext.js,.vue src test/unit", "build": "node build/build.js" }, "dependencies": { "vue": "^2.5.2" }, "devDependencies": { "autoprefixer": "^7.1.2", "babel-core": "^6.22.1", "babel-eslint": "^8.2.1", "babel-helper-vue-jsx-merge-props": "^2.0.3", "babel-jest": "^21.0.2", "babel-loader": "^7.1.1", "babel-plugin-dynamic-import-node": "^1.2.0", "babel-plugin-syntax-jsx": "^6.18.0", "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", "babel-plugin-transform-runtime": "^6.22.0", "babel-plugin-transform-vue-jsx": "^3.5.0", "babel-preset-env": "^1.3.2", "babel-preset-stage-2": "^6.22.0", "chalk": "^2.0.1", "copy-webpack-plugin": "^4.0.1", "css-loader": "^0.28.0", "eslint": "^4.15.0", "eslint-config-airbnb-base": "^11.3.0", "eslint-friendly-formatter": "^3.0.0", "eslint-import-resolver-webpack": "^0.8.3", "eslint-loader": "^1.7.1", "eslint-plugin-import": "^2.7.0", "eslint-plugin-vue": "^4.0.0", "extract-text-webpack-plugin": "^3.0.0", "file-loader": "^1.1.4", "friendly-errors-webpack-plugin": "^1.6.1", "html-webpack-plugin": "^2.30.1", "jest": "^22.0.4", "jest-serializer-vue": "^0.3.0", "node-notifier": "^5.1.2", "optimize-css-assets-webpack-plugin": "^3.2.0", "ora": "^1.2.0", "portfinder": "^1.0.13", "postcss-import": "^11.0.0", "postcss-loader": "^2.0.8", "postcss-url": "^7.2.1", "rimraf": "^2.6.0", "semver": "^5.3.0", "shelljs": "^0.7.6", "uglifyjs-webpack-plugin": "^1.1.1", "url-loader": "^0.5.8", "vue-jest": "^1.0.2", "vue-loader": "^13.3.0", "vue-style-loader": "^3.0.1", "vue-template-compiler": "^2.5.2", "webpack": "^3.6.0", "webpack-bundle-analyzer": "^2.9.0", "webpack-dev-server": "^2.9.1", "webpack-merge": "^4.1.0" }, "engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0" }, "browserslist": ["> 1%", "last 2 versions", "not ie <= 8"] } 

There are a lot of things here:

  • CDMY65CDMY - application/package name
  • CDMY66CDMY - application/package version
  • CDMY67CDMY - a brief description of the application/package
  • CDMY68CDMY - the main file (entry point) of the application
  • CDMY69CDMY - CDMY70CDMY value prevents accidental publishing of the application to CDMY71CDMY
  • CDMY72CDMY - a set of scripts (commands) that you can run (execute)
  • CDMY73CDMY - project dependencies
  • CDMY74CDMY - project dependencies, used only during development
  • CDMY75CDMY - versions on which the application/package is running
  • CDMY76CDMY - supported browsers (and their versions)

All of these properties are used by CDMY77CDMY.

Properties

In this section we will talk about some properties that you can use. We will use the term “package”, but most of the above also applies to applications.

Most properties are needed to publish the package to CDMY78CDMY, some to interact with the package.

Name (name)

Defines the name of the package.

For example:

"name": "test-project" 

The name must not exceed 214 characters, must not contain spaces, can consist only of lowercase letters (lower case), hyphens (-) and underscore (_).

This is because when published to CDMY79CDMY, a package is assigned a URL based on its name.

If the package is published on GitHub, specifying a link to the repository is considered good practice.

Author

Defines the author of the package.

For example:

{ "author": "Joe <joe@whatever.com> (https://whatever.com)" } 

or so:

{ "author": { "name": "Joe", "email": "joe@whatever.com", "url": "https://whatever.com" } } 

Collaborators

Defines one or more package collaborators. This property is an array of strings.

For example:

{ "contributors": ["Joe <joe@whatever.com> (https://whatever.com)"] } 

or so:

{ "contributors": [ { "name": "Joe", "email": "joe@whatever.com", "url": "https://whatever.com" } ] } 

Errors

Defines a link to instructions for solving problems, usually a GitHub issue tracker.

For example:

{ "bugs": "https://github.com/whatever/package/issues" } 

Home

Specifies the address of the home page.

For example:

{ "homepage": "https://whatever.com/package" } 

Version

Defines the current version of the package.

For example:

"version": "1.0.0" 

This property follows the standard of semantic versioning. This means that it should always consist of three numbers separated by periods: CDMY80CDMY.

The first digit is the major version, the second minor, the third patch.

Each number has a certain meaning: an update to eliminate errors is a patch, a release of backward compatible changes is a minor release, a major release can mean changes that are incompatible with the previous version.

License

Defines the package license.

For example:

"license": "MIT" 

Keywords

This property is an array of keywords associated with the package.

For example:

"keywords": [ "email", "machine learning", "ai" ] 

They help people find packages.

Description

Defines a brief description of the package.

For example:

"description": "A package to work with strings" 

When publishing a package in CDMY81CDMY, this property helps people understand what it is for.

Repository

Determines where the package source code is located.

For example:

"repository": "github:whatever/testing", 

Note the CDMY82CDMY prefix. There are other similar services:

"repository": "gitlab:whatever/testing", 

"repository": "bitbucket:whatever/testing", 

You can also define a version control system:

"repository": { "type": "git", "url": "https://github.com/whatever/testing.git" } 

You can specify several version control systems:

"repository": { "type": "svn", "url": "..." } 

main

Defines the main file (entry point) of the package.

When importing a package into an application, it is in this file that the application will search for exported modules.

For example:

"main": "src/main.js" 

private

Setting this property to CDMY83CDMY prevents the package from being accidentally published to CDMY84CDMY.

For example:

"private": true 

scripts

Defines a list of commands (scripts) that can be executed (run).

For example:

"scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", "unit": "jest --config test/unit/jest.conf.js --coverage", "test": "npm run unit", "lint": "eslint --ext.js,.vue src test/unit", "build": "node build/build.js" } 

These scripts are command line applications. You can run them using CDMY85CDMY or CDMY86CDMY, where CDMY87CDMY is the name of the command. For example: CDMY88CDMY.

You can use any name as the name of the command, the script will do everything you specify in it.

Dependencies

Defines a list of package dependencies.

When installing a package using npm or yarn:

npm install <PACKAGENAME> yarn add <PACKAGENAME> 

A record of this package will be automatically added to the property in question.

For example:

"dependencies": { "vue": "^2.5.2" } 

devDependencies

Defines a list of dependencies for development purposes.

They differ from CDMY89CDMY, because they are installed only on the developer's computer, and do not get into production.

When installing a package using npm or yarn:

npm install --save-dev <PACKAGENAME> yarn add --save-dev <PACKAGENAME> 

a record of it is automatically added to the property in question.

For example:

"devDependencies": { "autoprefixer": "^7.1.2", "babel-core": "^6.22.1" } 

engines

Determines which versions of Node.js or other tools the package/application is running on.

For example:

"engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0", "yarn": "^0.13.0" } 

browserlist

Defines a list of supported browsers (and their versions). This information is used by Babel, Autoprefixer and other tools to create polyfills and ensure compatibility with specified browsers.

For example:

"browserslist": [ "> 1%", "last 2 versions", "not ie <= 8" ] 

This setting means that you want to support the last two versions of all browsers that are used by more than 1% of people according to statistics CanIUse , with the exception of IE8 and older.

Special Properties

CDMY90CDMY may contain special properties for tools such as Babel, ESLint, etc.

Each of these tools has its own properties, for example, CDMY91CDMY, CDMY92CDMY and so on. See the related documentation for details on special properties.

Package Versions

In the examples above, you probably noticed entries like these: CDMY93CDMY, CDMY94CDMY. What do they mean? And what other version specifiers can I use?

These qualifiers are used to determine update conditions.

The rules are as follows:

  • CDMY95CDMY - the entry CDMY96CDMY means that only patch updates are allowed, i.e. CDMY97CDMY release is valid, but CDMY98CDMY release is not
  • CDMY99CDMY - the CDMY100CDMY entry means patch and minor updates are allowed
  • CDMY101CDMY - the CDMY102CDMY entry means that any updates are allowed
  • CDMY103CDMY - any new versions are valid
  • CDMY104CDMY - Similar or newer versions are acceptable
  • CDMY105CDMY - Similar or older versions are acceptable
  • CDMY106CDMY - any old versions are valid

Here are a couple more rules:

  • without a character at the beginning - only the specified version is allowed
  • CDMY107CDMY - only the latest version is valid

The indicated characters can be combined in various ways, for example: CDMY108CDMY.

Thank you for attention.

To be continued….

Source