Getting Started with Node and NPM

Let's start with the basics.

  1. Install Node.js: https://nodejs.org.

This code will need at least version 5.0.0, but we encourage you to run at least version 10.0.0. If you already had node installed, make sure the version is appropriate by running node -v

When you install Node.js, you'll want to ensure your PATH variable is set to your install path so you can call Node from anywhere.

  1. Create a new directory named hello-world, add a new app.js file:
/* app.js */
console.log('Hello World!');
  1. In the command prompt, run node app.js.

Your environment variables are set at the time when the command prompt is opened, so ensure to open a new command prompt since step 1 if you get any errors about Node not being found.

  1. Moving beyond from simple console applications...
/* app.js */

// Load the built-in 'http' module.
const http = require('http'); // Create an http.Server object, and provide a callback that fires after 'request' events.
// 创建一个http.Server对象,并提供在“请求”事件之后触发的回调
const server = http.createServer((request, response) => {
// Respond to the http request with "Hello World" and a basic header.
// 使用“hello World”和基本标头响应http请求
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World!\n');
}); // Try retrieving a port from an environment variable, otherwise fallback to 8080.
// 尝试从环境变量中检索端口,否则回退到8080
const port = process.env.PORT || 8080; // Start listening on the specified port and print out a url to visit.
// 开始在指定的端口上侦听并打印出要访问的URL
server.listen(port);
console.log(`Listening on http://localhost:${port}`);
  1. In the command prompt, run node app.js, and visit the url that's printed out to the console.

  2. To stop the application, run Ctrl+C.

Working with npm packages

As shown above, it's pretty impressive what you can do with so few lines of code in Node.js. Part of the philosophy of Node.js is that the core should remain as small as possible. It provides just enough built-in modules, such as filesystem and networking modules, to empower you to build scalable applications. However, you don't want to keep re-inventing the wheel every time for common tasks.

如上所示,使用Node.js中的几行代码可以做的事情令人印象深刻。 Node.js的部分哲学是核心应保持尽可能小。 它提供了足够的内置模块,例如文件系统和网络模块,使您能够构建可伸缩的应用程序。 但是,您不想每次都针对常规任务重新发明轮子

Introducing, npm!

npm is the package manager for JavaScript. npm ships with Node.js, so there's no need to install it separately.

npm是JavaScript的软件包管理器。 npm随Node.js一起提供,因此无需单独安装

Using an existing npm package

To get a sense for how to use npm packages in your app, let's try getting started with express, the most popular web framework for Node.js.

为了了解如何在应用程序中使用npm软件包,让我们尝试开始使用“express”(Node.js最受欢迎的Web框架)入门。

  1. Create a new directory entitled my-express-app, then install express from within that directory. When express is installed, the package and its dependencies appear under a node_modules folder.
C:\src> mkdir my-express-app
C:\src> cd my-express-app
C:\src\my-express-app> npm install express

We recommend starting with a short path like C:\src to work around any potential MAX_PATH issues.

  1. Now, create a new file, app.js. This code will load the express module we just installed, and use it to start a lightweight web server.
/* app.js */

const express = require('express');
const app = express(); app.get('/', (req, res) => {
res.send('Hello World!');
}); const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on http://localhost:${port}`);
});
  1. Start the app by running node app.js in the command line. Tada!

There are many more packages available at your disposal (200K and counting!). Head on over to https://www.npmjs.com to start exploring the ecosystem.

Most of the packages available via npm tend to be pure JavaScript, but not all of them. For instance, there's a small percentage of native module addons available via npm that provide Node.js bindings, but ultimately call into native C++ code. This includes packages with node-gyp, node-pre-gyp, and nan dependencies. In order to install and run these packages, some additional machine configuration is required (described below).

Managing npm dependencies

Once you start installing npm packages, you'll need a way to keep track of all of your dependencies. In Node.js, you do this through a package.json file.

一旦开始安装npm软件包,您将需要一种跟踪所有依赖项的方法。 在Node.js中,您可以通过“ package.json”文件来实现

  1. To create a package.json file, run the npm init in your app directory.
C:\src\my-express-app> npm init
  1. Npm will prompt you to fill in the details about your package.

    Npm会提示您填写有关包裹的详细信息

  2. In the package.json file, there is a "dependencies" section, and within it, an entry for "express". A value of "*" would mean that the latest version should be used. To add this entry automatically when you install a package, you can add a --save flag: npm install express --save.To save this as a dev dependency, use npm install express --save-dev.

    在package.json文件中,有一个“ dependencies”部分,其中有一个“ express”条目。 值“ *”将表示应使用最新版本。 要在安装软件包时自动添加该条目,可以添加一个--save标志:npm install express --save。要将其另存为dev依赖项,请使用npm install express --save-dev

If you only require a dependency as part of a development environment, then you could/should install the package in the "devDependencies". This is accomplished by using the --save-dev parameter. For example: npm install --save-dev mocha.

  1. Now that your packages are listed in package.json, npm will always know which dependencies are required for your app. If you ever need to restore your packages, you can run npm install from your package directory.

    现在,您的软件包已列在package.json中,npm将始终知道您的应用需要哪些依赖项。 如果您需要恢复软件包,可以从软件包目录运行npm install

When you distribute your application, we recommend adding the node_modules folder to .gitignore so that you don't clutter your repo with needless files. This also makes it easier to work with multiple platforms. If you want to keep things as similar as possible between machines, npm offers many options that enable you to fix the version numbers in package.json, and even more fine-grained control with npm-shrinkwrap.json.

分发应用程序时,建议将node_modules文件夹添加到.gitignore中,以免不必要的文件使您的回购变得混乱。 这也使得在多个平台上工作变得更加容易。 如果您想使机器之间的内容尽可能地相似,npm提供了许多选项,使您可以修复package.json中的版本号,甚至可以使用npm-shrinkwrap.json进行更细粒度的控制

Publishing npm packages to the registry

Once you've created a package, publishing it to the world is only one command away!

C:\src\my-express-app> npm publish

Use npm's private modules.

TODO Add description about how to authorize the machine using npm adduser.

Local vs. global packages

There are two types of npm packages - locally installed packages and globally installed packages. It's not an exact science, but in general...

npm软件包有两种类型:本地安装的软件包和全局安装的软件包。 这不是一门精确的科学,但总的来说...

  • Locally installed packages are packages that are specific to your application
  • 本地安装的软件包是特定于您的应用程序的软件包
  • Globally installed packages tend to be CLI tools and the like
  • 全局安装的软件包通常是CLI工具等

We went through locally installed packages above, and installing packages globally is very similar. The only difference is the -g command.

我们经历了上面的本地安装软件包,并且在全局范围安装软件包非常相似。 唯一的区别是-g命令

  1. npm install http-server -g will install the module globally.

The module will be installed to the path indicated by npm bin -g.

  1. Run http-server . to start a basic fileserver from any directory. On running this command , the server starts and runs on the localhost.

    运行http-server .以从任何目录启动基本文件服务器。 运行此命令后,服务器将启动并在本地主机上运行。

In fact the only difference when using -g is that executables are placed in a folder that is on the path. If you install without the -g option you can still access those executables in .\node_modules\.bin. This folder is automatically added to the path when any scripts defined in package.json are run. Doing this will help avoid version clashes when a project uses skrinkwrap or otherwise specifies the version of a module different to other projects. It also avoids the need for manual install instructions for some dependencies so a single "npm install" will do.

实际上,使用-g时唯一的区别是可执行文件位于路径上的文件夹中。 如果您未安装-g选项,则仍可以在. \ node_modules \ .bin中访问这些可执行文件。 当运行在package.json中定义的任何脚本时,该文件夹会自动添加到路径中。 当项目使用skrinkwrap或以其他方式指定与其他项目不同的模块版本时,这样做将有助于避免版本冲突。 它还避免了某些依赖项的手动安装说明,因此只需一个“ npm install”即可。

And much more!

Using nodemon

nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Use npm to install it:

nodemon是一个实用程序,它将监视源中的任何更改并自动重新启动服务器。 使用npm进行安装:

npm install -g nodemon

After installation, you can launch your application using nodemon. For example:

nodemon app.js

After this, you don't have to restart the Node server after making changes since nodemon will automatically restart it for you. If you're developing a web application, simply refresh your browser to examine your update. Pretty handy for development!

此后,您无需在进行更改后重新启动Node服务器,因为nodemon会自动为您重新启动它。 如果要开发Web应用程序,只需刷新浏览器以检查更新。 非常方便开发

Getting Started With Node and NPM的更多相关文章

  1. Node.js npm 详解

    一.npm简介 安装npm请阅读我之前的文章Hello Node中npm安装那一部分,不过只介绍了linux平台,如果是其它平台,有前辈写了更加详细的介绍. npm的全称:Node Package M ...

  2. CentOS 6.5安装Node.js, npm

    CentOS上可以通过下载*.tar.gz安装包的方式自己解压缩.编译的方式安装,同时还可以采用EPEL的方式安装: Node.js and npm are available from the Fe ...

  3. 使用 nvm 管理不同版本的 node 与 npm

    补充说明:Mac 下通过 brew install nvm 所安装的 nvm ,由于安装路径不同,无法正确启用.建议使用 brew uninstall nvm 卸载掉之后,通过本文的方案重新安装一次. ...

  4. Latest node.js & npm installation on Ubuntu 12.04

    转自:https://rtcamp.com/tutorials/nodejs/node-js-npm-install-ubuntu/ Compiling is way to go for many b ...

  5. Windows环境下 Node和NPM个性安装

    常拿自己的电脑常用来测试各种Bug,所以始终奋斗在XP.IE6的环境下.让我们在如此级别的环境下,开始Node之路吧~~ 在过去,Node.js一直不支持在Windows平台下原生编译,需要借助Cyg ...

  6. Mac环境下装node.js,npm,express

    1. 下载node.js for Mac 地址: http://nodejs.org/ 直接下载 pkg的,双击安装,一路点next,很容易就搞定了. 安装完会提醒注意 node和npm的路径是 /u ...

  7. Mac环境下装node.js,npm,express;(包括express command not found)

    1. 下载node.js for Mac 地址: http://nodejs.org/download/ 直接下载 pkg的,双击安装,一路点next,很容易就搞定了. 安装完会提醒注意 node和n ...

  8. Node.js npm

    Node程序包管理器(NPM)提供了以下两个主要功能: 在线存储库的Node.js包/模块,可搜索 search.nodejs.org 命令行实用程序来安装Node.js的包,做版本管理和Node.j ...

  9. ubuntu下nvm,node以及npm的安装与使用

    一:安装nvm 首先下载nvm,这里我们需要使用git,如果没有安装git,可以使用 sudo apt-get install git 来安装 git clone https://github.com ...

  10. node.js NPM 使用

    n=NPM是一个Node包管理和分发工具,已经成为了非官方的发布Node模块(包)的标准.有了NPM,可以很快的找到特定服务要使用的包,进行下载.安装以及管理已经安装的包.npms安装: 下载npm源 ...

随机推荐

  1. Python2 和 Python3的区别

    Python2 和 Python3的区别: 1.python2的默认编码方式是ascii码:python3的默认编码是utf-8. 如果出现乱码或者编码错误,可以使用以下编码在文件头来指定编码: #- ...

  2. 《图解 HTTP》 摘要一

    学习过程对书本的内容的摘要以及总结,逐步完善,带有个人理解成分. Web 及网络基础 使用 HTTP 协议访问 Web 客户端:通过获取请求获取服务资源的 Web 浏览器等 HTTP 全称:Htype ...

  3. 【java基础】01 计算机基础知识

    一.计算机基础知识 1. 计算机 1. 什么是计算机? 计算机在生活中的应用举例 计算机(Computer)全称:电子计算机,俗称电脑.是一种能够按照程序运行,自动.高速处理海量数据的现代化智能电子设 ...

  4. nodejs中httpserver的安装和使用

    首先来看一下官方的介绍: 大概意思是说:命令行HTTP服务器工具,用于提供本地文件,类似于python -mSimpleHTTPServe. 直白点的意思就是通过命令行启动的一个http服务器工具,它 ...

  5. 蓝桥杯2019初赛]迷宫(dfs版本)

    传送门 大意: 题目的意思还是模板的搜索,不同的是我们要记录路径了,而且是最短字典序最小的路径. 思路: 1.对于字典序最小,也就是说我们要尽量先往下走,然后是左- 这个很简单,因为在dfs中是顺序枚 ...

  6. P1191 矩形

    ------------恢复内容开始------------ 题意 给出一个\(n*n\)的矩阵,矩阵中,有些格子被染成白色,有些格子被染成黑色,现要求矩阵中白色矩形的数量 分割线 Ⅰ.暴力出奇迹!! ...

  7. 字典树变形 A - Gaby And Addition Gym - 101466A

    A - Gaby And Addition Gym - 101466A 这个题目是一个字典树的变形,还是很难想到的. 因为这题目每一位都是独立的,不会进位,这个和01字典树求最大的异或和是不是很像. ...

  8. 在web中使用shiro(会话管理,登出,shiro标签库的使用)

    在shiro的主配置文件中配置,登出的请求经过的过滤器就可以了,在shiro的过滤器中有一个名称为logout的过滤 器专门为我们处理登出请求: 一.shiro会话管理器 shiro中也提供了类似于w ...

  9. OpenWrt(LEDE)2020.4.29更新 UPnP+NAS+多拨+网盘+DNS优化+帕斯沃 无缝集成+软件包

    交流群:QQ 1030484865 电报:  t_homelede   固件说明 基于Lede OpenWrt R2020.4.8版本(源码截止2020.4.29)Lienol Feed及若干自行维护 ...

  10. STM32F767ZI NUCLEO144 基于CubeIDE快速开发入门指南

    刚入手的NUCLEO-F767ZI:整合官网资源,理清思路,便于快速进行快发: 文章目录 1 NUCLEO 系列 2 NUCLEO-F767ZI 3 环境搭建 3.1 Keil/IAR安装 3.2 C ...