IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> Official_Node.js -- introduction -> 正文阅读

[JavaScript知识库]Official_Node.js -- introduction

Introduction to Node.js

Introduction to Node.js

Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!

Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.

A Node.js app runs in 1?? a single process, without creating a new thread for every request.

Node.js provides a set of asynchronous I/O primitives in its standard library that 2?? prevent JavaScript code from blocking

generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will 3?? resume the operations when the response comes back.

This allows Node.js to handle thousands of 4?? concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.

In Node.js the new ECMAScript standards can be used without problems, as you don’t have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.

An Example Node.js Application

The most common example Hello World of Node.js is a web server:

const http = require('http')

const hostname = '127.0.0.1'
const port = 998

const server = http.createServer((req, res) => {
    res.statusCode = 200
    res.setHeader('Content-Type', 'text/plain')
    res.end('Hello World!\n')
})

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`)
})

This code first includes the Node.js http module

Node.js has a fantastic standard library, including first-class support for networking.

The createServer() method of http 🥅 ? creates a new HTTP server and returns it.

The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running.

Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object).

Those 2 objects are essential to handle the HTTP call.

The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.

The second is used to return data to the caller.

In this case with:

res.statusCode = 200

we set the statusCode property to 200, to indicate a successful response.

We set the Content-Type header:

res.setHeader('Content-Type', 'text/plain')

and we close the response, adding the content as an argument to end():

res.end('Hello World\n')

A brief history of Node.js

JavaScript is a programming language that was created at Netscape as a scripting tool to manipulate web pages inside their browser, Netscape Navigator.

Part of the business model of Netscape was to sell Web Servers, which included an environment called Netscape LiveWire that could 👯 create dynamic pages using server-side JavaScript. Unfortunately, Netscape LiveWire wasn’t very successful and server-side JavaScript wasn’t popularized until recently, by the introduction of Node.js.

One key factor that led to the rise of Node.js was the timing. Just a few years earlier, JavaScript had started to be considered as a more serious language, thanks to “Web 2.0” applications (such as Flickr, Gmail, etc.) that showed the world what a modern experience on the web could be like.

JavaScript engines also became considerably better as many browsers competed to offer users the best performance. Development teams behind major browsers worked hard to offer better support for JavaScript and find ways to ?? make JavaScript run faster. The engine that Node.js uses under the hood, V8 (also known as Chrome V8 for being the open-source JavaScript engine of The Chromium Project), improved significantly due to this competition.

Node.js happened to be built in the right place and right time, but luck isn’t the only reason why it is popular today. It introduces a lot of innovative thinking and approaches for JavaScript server-side development that have already helped many developers.

2009

  • Node.js is born
  • The first form of npm is created

2010

2011

  • npm hits version 1.0
  • Larger companies start adopting Node.js: LinkedIn, Uber, etc.
  • hapi is born

2012

  • Adoption continues very rapidly

2013

  • First big blogging platform using Node.js: Ghost
  • Koa is born

2014

  • The Big Fork: io.js is a major fork of Node.js, with the goal of introducing ES6 support and moving faster

2015

  • The Node.js Foundation is born
  • IO.js is merged back into Node.js
  • npm introduces private modules
  • Node.js 4 (versions 1, 2 and 3 never previously released)

2016

2017

  • npm focuses more on security
  • Node.js 8
  • HTTP/2
  • V8 introduces Node.js in its testing suite, officially making Node.js a target for the JS engine, in addition to Chrome
  • 3 billion npm downloads every week

2018

  • Node.js 10
  • ES modules .mjs experimental support
  • Node.js 11

2019

  • Node.js 12
  • Node.js 13

2020

  • Node.js 14
  • Node.js 15

2021

  • Node.js 16

nvm is a popular way to run Node.js. It allows you to easily switch the Node.js version, and install new versions to try and easily rollback if something breaks, for example.

Differences between Node.js and the Browser

Both the browser and Node.js use JavaScript as their programming language.

Building apps that run in the browser is a completely different thing than building a Node.js application.

Despite the fact that it’s always JavaScript, there are some key differences that make the experience radically different.

From the perspective of a frontend developer who extensively uses JavaScript, Node.js apps bring with them a huge advantage

1?? the comfort of programming everything - the frontend and the backend - in a single language.

You have a huge opportunity because we know how hard it is to fully, deeply learn a programming language, and by using the same language to perform all your work on the web - both on the client and on the server, you’re in a unique position of advantage.

What changes is the ecosystem.

In the browser, most of the time what you are doing is interacting with the DOM, or other Web Platform APIs like Cookies. Those do not exist in Node.js, of course. You don’t have the document, window and all the other objects that are provided by the browser.

And in the browser, we don’t have all the 2??nice APIs that Node.js provides through its modules, like the filesystem access functionality.

Another big difference is that in Node.js you 3?? control the environment. Unless you are building an open source application that anyone can deploy anywhere, you know which version of Node.js you will run the application on. Compared to the browser environment, where you don’t get the luxury to choose what browser your visitors will use, this is very convenient.

This means that you can write all the modern ES6-7-8-9 JavaScript that your Node.js version supports.

Since JavaScript moves so fast, but browsers can be a bit slow to upgrade, sometimes on the web you are stuck with using older JavaScript / ECMAScript releases.

You can use Babel to transform your code to be ES5-compatible before shipping it to the browser, but in Node.js, you won’t need that.

Another difference is that Node.js 4?? uses the CommonJS module system, while in the browser we are starting to see the ES Modules standard being implemented.

In practice, this means that for the time being you use require() in Node.js and import in the browser.

The V8 JavaScript Engine

V8 is the name of the JavaScript engine that powers Google Chrome. It’s the thing that takes our JavaScript and executes it while browsing with Chrome.

V8 provides the runtime environment in which JavaScript executes. The DOM, and the other Web Platform APIs are provided by the browser.

The cool thing is that the JavaScript engine is 👦 independent of the browser in which it’s hosted. This key feature enabled the rise of Node.js. V8 was chosen to be the engine that powered Node.js back in 2009, and as the popularity of Node.js exploded, V8 became the engine that now powers an incredible amount of server-side code written in JavaScript.

The Node.js ecosystem is huge and thanks to V8 which also powers desktop apps, with projects like Electron.

The quest for performance

V8 is written in C++, and it’s continuously improved. It is portable and runs on Mac, Windows, Linux and several other systems.

In this V8 introduction, we will ignore the implementation details of V8: they can be found on more authoritative sites (e.g. the V8 official site), and they change over time, often radically.

V8 is always evolving, just like the other JavaScript engines around, to speed up the Web and the Node.js ecosystem.

On the web, there is a race for performance that’s been going on for years, and we (as users and developers) benefit a lot from this competition because we 👊 get faster and more optimized machines year after year.

Compilation

JavaScript is generally considered an interpreted language, but modern JavaScript engines no longer just interpret JavaScript, they compile it.

This has been happening since 2009, when the SpiderMonkey JavaScript compiler was added to Firefox 3.5, and everyone followed this idea.

JavaScript is internally compiled by V8 with 🕛 just-in-time (JIT) compilation to speed up the execution.

This might seem counter-intuitive, but since the introduction of Google Maps in 2004, JavaScript has evolved from a language that was generally executing a few dozens of lines of code to complete applications with thousands to hundreds of thousands of lines running in the browser.

Our applications now can run for hours inside a browser, rather than being just a few form validation rules or simple scripts.

In this new world, compiling JavaScript makes perfect sense because while it might take a little bit more to have the JavaScript ready, once done it’s going to be much more performant than purely interpreted code.

How to exit from a Node.js program

The process core module provides a handy method that allows you to programmatically exit from a Node.js program: process.exit().

When Node.js runs this line, the process is immediately forced to terminate.

This means that any callback that’s pending, any network request still being sent, any filesystem access, or processes writing to stdout or stderr - all is going to be ungracefully terminated right away.

If this is fine for you, you can pass an integer that signals the operating system the exit code:

process.exit(1)

By default the exit code is 0, which means success. Different exit codes have different meaning, which you might want to use in your own system to have the program communicate to other programs.

You can read more on exit codes at https://nodejs.org/api/process.html#process_exit_codes

You can also set the process.exitCode property:

process.exitCode = 1

and when the program ends, Node.js will return that exit code.

A program will gracefully exit when all the processing is done.

Many times with Node.js we start servers, like this HTTP server:

At first: npm install express

const express = require('express')
const app = express()

app.get('/', (req, res) => {
  res.send('Hi!')
})

app.listen(3000, () => console.log('Server ready'))

Express is a framework that uses the http module under the hood, app.listen() returns an instance of http. You would use https.createServer if you needed to serve your app using HTTPS, as app.listen only uses the http module.

This program is never going to end. If you call process.exit(), any currently pending or running request is going to be aborted. This is not nice.

In this case you need to send the command a SIGTERM signal, and handle that with the process signal handler:

Note: process does not require a “require”, it’s automatically available.

const express = require('express')

const app = express()

app.get('/', (req, res) => {
  res.send('Hi!')
})

const server = app.listen(3000, () => console.log('Server ready'))

process.on('SIGTERM', () => {
  server.close(() => {
    console.log('Process terminated')
  })
})

What are signals? Signals are a POSIX intercommunication system: a notification sent to a process in order to 🥅notify it of an event that occurred.

SIGKILL is the signal that tells a process to immediately terminate, and would ideally act like process.exit().

SIGTERM is the signal that tells a process to gracefully terminate. It is the signal that’s sent from process managers like upstart or supervisord and many others.

You can send this signal from inside the program, in another function:

process.kill(process.pid, 'SIGTERM')

Or from another Node.js running program, or any other app running in your system that knows the PID of the process you want to terminate.

How to read environment variables from Node.js

The process core module of Node.js provides the env property which hosts all the environment variables that were set at the moment the process was started.

The below code runs app.js and set USER_ID

process.env.USER_ID="239482"

That will pass the user USER_ID as 239482 and the USER_KEY as foobar. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

Note: process does not require a “require”, it’s automatically available.

Here is an example that accesses the USER_ID and USER_KEY environment variables, which we set in above code.

console.log(process.env.USER_ID);  // "239482"

In the same way you can access any custom environment variable you set.

If you have multiple environment variables in your node project, you can also create an .env file in the root directory of your project, and then use the dotenv package to load them during runtime.

# .env fileUSER_ID="239482"USER_KEY="foobar"NODE_ENV="development"

In your js file

require('dotenv').config();process.env.USER_ID // "239482"process.env.USER_KEY // "foobar"process.env.NODE_ENV // "development"

You can also run your js file with node -r dotenv/config index.js command if you don’t want to import the package in your code.

How to use the Node.js REPL

use node in REPL mode:

node

Note: REPL also known as Read Evaluate Print Loop is a programming language environment (basically a console window) that takes single expression as user input and returns the result back to the console after execution.

Start simple and enter

> console.log('test')testundefined>

Use the tab to autocomplete

The cool thing about the REPL is that it’s interactive.

As you write your code, if you press the tab key the REPL will try to autocomplete what you wrote to match a variable you already defined or a predefined one.

Exploring JavaScript objects

Try entering the name of a JavaScript class, like Number, add a dot and press double tab.

The REPL will print all the properties and methods you can access on that class

Explore global objects

You can inspect the globals you have access to by typing global. and pressing tab

The _ special variable

If after some code you type _, that is going to print the result of the last operation.

Dot commands

The REPL has some special commands, all starting with a dot .. They are

  • .help: shows the dot commands help
  • .editor: enables editor mode, to write multiline JavaScript code with ease. Once you are in this mode, enter ctrl-D to run the code you wrote.
  • .break: when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C.
  • .clear: resets the REPL context to an empty object and clears any multi-line expression currently being input.
  • .load: loads a JavaScript file, relative to the current working directory
  • .save: saves all you entered in the REPL session to a file (specify the filename)
  • .exit: exits the repl (same as pressing ctrl-C two times)

The REPL knows when you are typing a multi-line statement without the need to invoke .editor.

For example if you start typing an iteration like this:

[1, 2, 3].forEach(num => {

and you press enter, the REPL will go to a new line that starts with 3 dots, indicating you can now continue to work on that block.

... console.log(num)... })

If you type .break at the end of a line, the multiline mode will stop and the statement will not be executed.

Node.js, accept arguments from the command line

You can pass any number of arguments when invoking a Node.js application using

node app.js

Arguments can be standalone or have a key and a value.

For example:

node app.js joe

or

node app.js name=joe

This changes how you will retrieve this value in the Node.js code.

The way you retrieve it is using the process object built into Node.js.

It exposes an argv property, which is an array that contains all the command line invocation arguments.

The first element is the full path of the node command.

The second element is the full path of the file being executed.

All the additional arguments are present from the third position going forward.

You can iterate over all the arguments (including the node path and the file path) using a loop:

process.argv.forEach((val, index) => {  console.log(`${index}: ${val}`)})

You can get only the additional arguments by creating a new array that excludes the first 2 params:

const args = process.argv.slice(2)

If you have one argument without an index name, like this:

node app.js joe

you can access it using

const args = process.argv.slice(2)args[0]

In this case:

node app.js name=joe

args[0] is name=joe, and you need to parse it. The best way to do so is by using the minimist library, which helps dealing with arguments:

const args = require('minimist')(process.argv.slice(2))args['name'] //joe

This time you need to use double dashes before each argument name:

node app.js --name=joe

Output to the command line using Node.js

Node.js provides a console module which provides tons of very useful ways to interact with the command line.

It is basically the same as the console object you find in the browser.

The most basic and most used method is console.log(), which prints the string you pass to it to the console.

If you pass an object, it will render it as a string.

You can pass multiple variables to console.log, for example:

const x = 'x'const y = 'y'console.log(x, y)

and Node.js will print both.

We can also format pretty phrases by passing variables and a format specifier.

For example:

console.log('My %s has %d years', 'cat', 2)
  • %s format a variable as a string
  • %d format a variable as a number
  • %i format a variable as its integer part only
  • %o format a variable as an object

Example:

console.log('%o', Number)

Clear the console

console.clear() clears the console (the behavior might depend on the console used)

Counting elements

console.count() is a handy method.

count the number of times a string is printed, and print the count next to it

const x = 1const y = 2console.count(x)console.count(x)console.count(x)console.count(y)console.count(y)

1: 1
1: 2
1: 3
2: 1
2: 2

The console.countReset() method resets counter used with console.count().

const oranges = ['orange', 'orange']
const apples = ['just one apple']
oranges.forEach(fruit => {
    console.count(fruit)
})
apples.forEach(fruit => {
    console.count(fruit)
})

console.countReset('orange')

oranges.forEach(fruit => {
    console.count(fruit)
})

orange: 1
orange: 2
just one apple: 1
orange: 1
orange: 2

Print the stack trace

There might be cases where it’s useful to print the call stack trace of a function, maybe to answer the question how did you reach that part of the code?

You can do so using console.trace():

const function2 = () => console.trace()
const function1 = () => function2()
function1()

Calculate the time spent

You can easily calculate how much time a function takes to run, using time() and timeEnd()

const doSomething = () => console.log('test')const measureDoingSomething = () => {    console.time('doSomething()')    //do something, and measure the time it takes    doSomething()    console.timeEnd('doSomething()')}measureDoingSomething()

stdout and stderr

As we saw console.log is great for printing messages in the Console. This is what’s called the standard output, or stdout.

console.error prints to the stderr stream.

It will not appear in the console, but it will appear in the error log.

Color the output

You can color the output of your text in the console by using escape sequences. An escape sequence is a set of characters that identifies a color.

Example:

console.log('\x1b[33m%s\x1b[0m', 'hi!')

You can try that in the Node.js REPL, and it will print hi! in yellow.

However, this is the low-level way to do this. The simplest way to go about coloring the console output is by using a library. Chalk is such a library, and in addition to coloring it also helps with other styling facilities, like making text bold, italic or underlined.

You install it with npm install chalk, then you can use it:

const chalk = require('chalk')console.log(chalk.yellow('hi!'))

Using chalk.yellow is much more convenient than trying to remember the escape codes, and the code is much more readable.

Check the project link posted above for more usage examples.

Create a progress bar

Progress is an awesome package to create a progress bar in the console. Install it using npm install progress

This snippet creates a 10-step progress bar, and every 100ms one step is completed. When the bar completes we clear the interval:

const ProgressBar = require('progress')const bar = new ProgressBar(':bar', { total: 10 })const timer = setInterval(() => {    bar.tick()    if (bar.complete) {        clearInterval(timer)    }}, 100)

Accept input from the command line in Node.js

How to make a Node.js CLI program interactive?

Node.js since version 7 provides the readline module to perform exactly this: get input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time.

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

This piece of code asks the username, and once the text is entered and the user presses enter, we send a greeting.

The question() method shows the first parameter (a question) and 🤔waits for the user input. It calls the callback function once enter is pressed.

In this callback function, we close the readline interface.

readline offers several other methods, and I’ll let you check them out on the package documentation linked above.

If you need to require a password, it’s best not to echo it back, but instead show a * symbol.

The simplest way is to use the readline-sync package which is very similar in terms of the API and handles this out of the box.

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

You can install it using npm install inquirer, and then you can replicate the above code like this:

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

Inquirer.js lets you do many things like asking multiple choices, having radio buttons, confirmations, and more.

It’s worth knowing all the alternatives, especially the built-in ones provided by Node.js, but if you plan to take CLI input to the next level, Inquirer.js is an optimal choice.

Expose functionality from a Node.js file using exports

Node.js has a built-in module system.

A Node.js file can import functionality exposed by other Node.js files.

When you want to import something you use

const library = require('./library')

to import the functionality exposed in the library.js file that resides in the current file folder.

In this file, functionality must be exposed before it can be imported by other files.

Any other object or variable defined in the file by default is private and not exposed to the outer world.

This is what the module.exports API offered by the module system allows us to do.

When you assign an object or a function as a new exports property, that is the thing that's being exposed, and as such, it can be imported in other parts of your app, or in other apps as well.

You can do so in 2 ways.

The first is to assign an object to module.exports, which is an object provided out of the box by the module system, and this will make your file export just that object:

// car.jsconst car = {  brand: 'Ford',  model: 'Fiesta'}module.exports = car// index.jsconst car = require('./car')

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

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

or directly

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

And in the other file, you’ll use it by referencing a property of your import:

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

or

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

What’s the difference between module.exports and exports?

The first exposes 👪 ? the object it points to. The latter exposes 👨the properties of the object it points to.

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

module.exports

const car = {    brand: 'Ford',    model: 'Fiesta'}const hoho = "haha"// { carCusArg: { brand: 'Ford', model: 'Fiesta' }, hoho: 'haha' }module.exports = { carCusArg: car, hoho }// will be no work when use module.exportsexports.carCusArg2 = car

Output: { carCusArg: { brand: ‘Ford’, model: ‘Fiesta’ }, hoho: ‘haha’ }

An introduction to the npm package manager

Introduction to npm

npm is the standard package manager for Node.js.

In January 2017 over 350000 packages were reported being listed in the npm registry, making it the biggest single language code repository on Earth, and you can be sure there is a package for (almost!) everything.

It started as a way to download and manage dependencies of Node.js packages, but it has since become a tool used also in frontend JavaScript.

There are many things that npm does.

Yarn and pnpm are alternatives to npm cli. You can check them out as well.

Downloads

npm manages downloads of dependencies of your project.

Installing all dependencies

If a project has a package.json file, by running

npm install

it will install everything the project needs, in the node_modules folder, creating it if it’s not existing already.

Installing a single package

You can also install a specific package by running

npm install <package-name>

Furthermore, since npm 5, this command adds <package-name> to the package.json file dependencies. Before version 5, you needed to add the flag --save.

Often you’ll see more flags added to this command:

  • --save-dev installs and adds the entry to the package.json file devDependencies
  • --no-save installs but does not add the entry to the package.json file dependencies

The difference between devDependencies and dependencies is that the former contains development tools, like a testing library, while the latter is bundled with the app in production.

Updating packages

Updating is also made easy, by running

npm update

npm will check all packages for a newer version that satisfies your versioning constraints.

You can specify a single package to update as well:

npm update <package-name>

Versioning

In addition to plain downloads, npm also manages versioning, so you can specify any specific version of a package, or require a version higher or lower than what you need.

Many times you’ll find that a library is only compatible with a major release of another library.

Or a bug in the latest release of a lib, still unfixed, is causing an issue.

Specifying an explicit version of a library also helps to keep everyone on the same exact version of a package, so that the whole team runs the same version until the package.json file is updated.

In all those cases, versioning helps a lot, and npm follows the semantic versioning (semver) standard.

Running Tasks

The package.json file supports a format for specifying command line tasks that can be run by using

npm run <task-name>

For example:

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

It’s very common to use this feature to run 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",  }}

So instead of typing those long commands, which are easy to forget or mistype, you can run

$ npm run watch$ npm run dev$ npm run prod

Where does npm install the packages?

When you install a package using npm you can perform 2 types of installation:

  • a local install
  • a global install

By default, when you type an npm install command, like:

npm install lodash

the package is installed in the current file tree, under the node_modules subfolder.

As this happens, npm also adds the lodash entry in the dependencies property of the package.json file present in the current folder.

A global installation is performed using the -g flag:

npm install -g lodash

When this happens, npm won’t install the package under the local folder, but instead, it will use a global location.

Where, exactly?

The npm root -g command will tell you where that exact location is on your machine.

On macOS or Linux this location could be /usr/local/lib/node_modules. On Windows it could be C:\Users\YOU\AppData\Roaming\npm\node_modules

If you use nvm to manage Node.js versions, however, that location would differ.

I for example use nvm and my packages location was shown as /Users/joe/.nvm/versions/node/v8.9.0/lib/node_modules.

The package.json guide

If you work with JavaScript, or you’ve ever interacted with a JavaScript project, Node.js or a frontend project, you surely met the package.json file.

What’s that for? What should you know about it, and what are some of the cool things you can do with it?

The package.json file is kind of a manifest for your project. It can do a lot of things, completely unrelated. It’s a central repository of 1?? configuration for tools, for example. It’s also where npm and yarn 2?? store the names and versions for all the installed packages.

The file structure

Here’s an example package.json file:

{}

It’s empty! There are no fixed requirements of what should be in a package.json file, for an application. The only requirement is that it respects the JSON format, otherwise it cannot be read by programs that try to access its properties programmatically.

If you’re building a Node.js package that you want to distribute over npm things change radically, and you must have a set of properties that will help other people use it. We’ll see more about this later on.

This is another package.json:

{
  "name": "test-project"
}

It defines a name property, which tells the name of the app, or package, that’s contained in the same folder where this file lives.

  • version indicates the current version
  • name sets the application/package name
  • description is a brief description of the app/package
  • main set the entry point for the application
  • private if set to true prevents the app/package to be accidentally published on npm
  • scripts defines a set of node scripts you can run
  • dependencies sets a list of npm packages installed as dependencies
  • devDependencies sets a list of npm packages installed as development dependencies
  • engines sets which versions of Node.js this package/app works on
  • browserslist is used to tell which browsers (and their versions) you want to support

All those properties are used by either npm or other tools that we can use.

Properties breakdown

This section describes the properties you can use in detail. We refer to “package” but the same thing applies to local applications which you do not use as packages.

Most of those properties are only used on https://www.npmjs.com/, others by scripts that interact with your code, like npm or others.

name

Sets the package name.

Example:

"name": "test-project"

The name must be less than 214 characters, must not have spaces, it can only contain lowercase letters, hyphens (-) or underscores (_).

This is because when a package is published on npm, it gets its own URL based on this property.

If you published this package publicly on GitHub, a good value for this property is the GitHub repository name.

version

Indicates the current version of the package.

Example:

"version": "1.0.0"

This property follows the semantic versioning (semver) notation for versions, which means the version is always expressed with 3 numbers: x.x.x.

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

There is a meaning in these numbers: a release that only 1?? fixes bugs is a patch release, a release that 2??introduces backward-compatible changes is a minor release, a major release can 3?? have breaking changes.

main

Sets the entry point for the package.

When you import this package in an application, that’s where the application will ?? search for the module exports.

Example:

"main": "src/main.js"

The package-lock.json file

The goal of package-lock.json file is to keep track of the exact version of every package that is installed so that a product is 100% reproducible in the same way even if packages are updated by their maintainers.

Find the installed version of an npm package

To see the version of all installed npm packages, including their dependencies: npm list

npm list -g is the same, but for globally installed packages.

To get only your top-level packages (basically, the ones you told npm to install and you listed in the package.json), run npm list --depth=0

Install an older version of an npm package

npm install cowsay@1.2.0

global

npm install -g webpack@4.16.4

listing all the previous versions of a package. You can do it with npm view <package> versions:

 npm view vue versions

Update all the Node.js dependencies to their latest version

If there is a new minor or patch release and we type npm update, the installed version is updated, and the package-lock.json file diligently filled with the new version.

npm update will update the package.json with the updated version.

Use npm update --no-save to not update package.json.

To 👀 discover new releases of the packages, you run npm outdated.

Semantic Versioning using npm

When you make a new release, you don’t just up a number as you please, but you have rules:

  • you up the major version when you make ? incompatible API changes

  • you up the minor version when you 🎢 add functionality in a backward-compatible manner

  • you up the patch version when you make backward-compatible 🐛 bug fixes

  • ^: It will only do updates that do not change the leftmost non-zero number.

    ? If you write ^0.13.0, when running npm update, it can update to 0.13.1, 0.13.2, and so on, but not to 0.14.0 or above.

    ? But if you wirte ^1.13.0,when runningnpm update it can update to 1.13.11.14.0 and so on

  • ~: if you write ~0.13.0 when running npm update it can update to patch releases: 0.13.1 is ok, but 0.14.0 is not.

Uninstalling npm packages

npm uninstall <package-name>

Using the -S flag, or --save, this operation will also remove the reference in the package.json file.

npm uninstall -g <package-name>

npm global or local packages

The main difference between local and global packages is this:

  • local packages are installed in the directory where you run npm install <package-name>, and they are put in the node_modules folder under this directory
  • global packages are all put in a single place in your system (exactly where depends on your setup), regardless of where you run npm install -g <package-name>

In your code you can only require local packages:

require('package-name')

so when should you install in one way or another?

In general, all packages should be installed locally.

This makes sure you can have dozens of applications in your computer, all running a different version of each package if needed.

Updating a global package would make all your projects use the new release, and as you can imagine this might cause nightmares in terms of maintenance, as some packages might break compatibility with further dependencies, and so on.

All projects have their own local version of a package, even if this might appear like a waste of resources, it’s minimal compared to the possible negative consequences.

A package should be installed globally when it provides an executable command that you run from the shell (CLI), and it’s reused across projects.

You can also install executable commands locally and run them using npx, but some packages are just better installed globally.

You probably have some packages installed globally already on your system. You can see them by running

npm list -g --depth 0

on your command line.

npm dependencies and devDependencies

When you install an npm package using npm install <package-name>, you are installing it as a dependency.

The package is automatically listed in the package.json file, under the dependencies list (as of npm 5: before you had to manually specify --save ). -S

When you add the -D flag, or --save-dev, you are installing it as a development dependency, which adds it to the devDependencies list.


Development dependencies are intended as development-only packages, that are ?unneeded in production. For example testing packages, webpack or Babel.

When you go in production, if you type npm install and the folder contains a package.json file, they are installed, as npm assumes this is a development deploy.

You need to set the --production flag (npm install --production) to avoid installing those ? development dependencies.

npx

npx allows you to run that npm command without installing it first. If the command isn’t found, npx will install it into a central cache:

npx cowsay "Hello"

will do the job.

Other scenarios include:

  • running the vue CLI tool to create new applications and run them: npx @vue/cli create my-vue-app
  • creating a new React app using create-react-app: npx create-react-app my-react-app

and many more.

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-08-01 14:24:51  更:2021-08-01 14:27:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/3 14:52:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码