zoukankan      html  css  js  c++  java
  • Node.js && npm

    how to Install and Use Node.js and npm (Mac, Windows, Linux)

     In order to use almost any development tools based in JavaScript, you'll need to know how to use npm and Node.js. GulpGrunt, and Webpack are a few examples of popular technologies you may have heard of that require a knowledge of the Node ecosystem.

    I find myself writing about this over and over again in the prerequisites of an article I've begun to write. I'd prefer to write one definitive guide to refer to in the future, so here it is.

    Prerequisites

    • Basic command line proficiency. Don't skip this step! If you don't know how to use the command line, you'll be fighting an uphill battle. The provided tutorial has everything you need to know.

    Goals

    • Learn what Node.js and npm are
    • Set up Node.js and npm on Windows and Mac

    What is Node.js?

    JavaScript is a client-side programming language, which means it’s processed in the browser. With the advent of Node.js, JavaScript can also be used as a server-side language.

    What is npm?

    npm doesn't stand for Node Package Manager*, which means it’s the tool to connect to the repository containing all the Node.js programs, plugins, modules and so on.

    *npm actually does not stand for "Node Package Manager" but essentially that's what it is and does, so most people refer to it that way.

    Local vs. Global

    This is the most confusing concept to understand at first, so it's important to let this settle in. Traditionally, you're used to globally installing any sort of program or software on your computer. If you want Spotify, you'll download Spotify, and then it will be available to you.

    With npm, you will have some global installs, but mostly everything will be done on a local project basis, meaning you'll have to install everything you need for each project in its own directory. If you want to have a project running Gulp and Sass, you'll create a directory, with a new npm install.

    For future reference, any global installations will have the -g flag.

    Installation on Windows

    Installing everything on Windows is a breeze.

    Install Node.js and npm

    Node.js and npm can be installed from a download link. Go to the Node installation page, and download the Node installer. I have a 64-bit Windows 10 OS, so I chose that one.

    Once it's done, you can test to see both node and npm functioning by opening PowerShell (or any shell) and typing node -v and npm -v, which will check the version number.

    Create a Project

    Navigate to the directory in which you want your project to exist - in my case, sites/node-test.

    cd sites/node-test

    Now initalize a new project with npm.(创建node.js模块)

    npm init
    • 在项目中引导创建一个package.json文件。
      • 安装包的信息可保持到项目的package.json文件中,以便后续的其它的项目开发或者他人合作使用,package.json在项目中是必不可少的。
    • 和git的初始化仓库是不是很像。这样初始化之后,项目目录下会自动生成一个package.json文件。
    • 注意的是,npm init命令后,npm会询问你一系列问题,当你填入答案后才会正式结束初始化,如果不太想自定义一些关于项目的描述,可以不敲npm init,而是直接敲npm init --yes
      • 命令行中将会提示 package.json 字段中需要你输入的值。
        • 名称(name) 和 版本(version) 这两个字段是必填的。
        • 你还需要输入 入口文件字段(main) 字段,默认值是 index.js

    First, it will ask for a package name.

    node-test

    Version number.

    1.0.0

    Description.

    Creating my first "Hello, World!" Node project.

    The rest you can just press enter and skip. Now you'll notice we have a package.json file that contains all the information we entered.

    package.json
    {
      "name": "node-test",
      "version": "1.0.0",
      "description": "Creating my first "Hello, World!" Node project.",
      "main": "index.js",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
      },
      "author": "Tania Rascia",
      "license": "ISC"
    }

    A package.json is a file that contains metadata about the project, and handles the dependencies (additional software and modules) of the project.

    在index.js文件中,添加一个函数,作为 exports对象的一个属性。这样,require 此文件之后,这个函数在其他代码中就可以使用了。

    Package.json 属性说明

    • name - 包名。

    • version - 包的版本号。

    • description - 包的描述。

    • homepage - 包的官网 url 。

    • author - 包的作者姓名。

    • contributors - 包的其他贡献者姓名。

    • dependencies - 依赖包列表。如果依赖包没有安装,npm 会自动将依赖包安装在 node_module 目录下。

    • repository - 包代码存放的地方的类型,可以是 git 或 svn,git 可在 Github 上。

    • main - main 字段指定了程序的主入口文件,require('moduleName') 就会加载这个文件。这个字段的默认值是模块根目录下面的 index.js。

    • keywords - 关键字

    Now, we're going to install our first dependency - a very important and useful package called left-pad, which will add white space to the left side of a string, adding up to a number.

    For example, writing this:

    leftPad('String', 10)

    Will output this:

    console
    String

    left-pad is a package on npm, which as we stated previously contains the registry for all publicly available packages.

    Install dependencies ,下载安装依赖包

    前面有提到初始化项目,可视为创建node.js模块的时候,会生成package.json文件。

    而我们的项目显然会在途中用上很多模块,这些模块是不便全部上传到github仓库供用户下载的(github有限制仓库大小不能超过100M)。且用户还需自己手动安装这些依赖包也容易出错。

    为此,npm提供了很大的便利

    To install a dependency with npm, we use the command npm install dependency-name-here. Now, simply running npm install will download the dependency, but it won't save it to the project. Since we've already created our package.json, we'll use the flag --save to install the dependency and add it to package.json.

    npm install left-pad --save # 安装一个本地包,如果加上-g选项则是安装全局包

    有两种方式用来安装 npm 包:本地安装和全局安装。至于选择哪种方式来安装,取决于我们如何使用这个包。

    • 如果你自己的模块依赖于某个包,并通过 Node.js 的 require 加载,那么你应该选择本地安装,这种方式也是 npm install 命令的默认行为。
    • 如果你想将包作为一个命令行工具,(比如 grunt CLI),那么你应该选择全局安装

    本地安装和全局安装区别

    • 本地安装
      • 1. 将安装包放在 ./node_modules 下(运行 npm 命令时所在的目录),如果没有 node_modules 目录,会在当前执行 npm 命令的目录下生成 node_modules 目录。
      • 2. 可以通过 require() 来引入本地安装的包。
    • 全局安装
      • 1. 将安装包放在 /usr/local 下或者你 node 的安装目录。
      • 2. 可以直接在命令行里使用。

    如果你希望具备两者功能,则需要在两个地方安装它或使用 npm link

    As long as you ran this command inside the project directory, it will successfully install the dependency by creating a node_modules directory. It will also create a package-lock.json file, which we can ignore. Finally, it updated our package.json file with a new line.

    安装好之后,express 包就放在了工程目录下的 node_modules 目录中,因此在代码中只需要通过 require('express') 的方式就好,无需指定第三方包路径。

    同理,你在npm中下载别人发布的项目或模块后,也需要npm install来安装好依赖以便运行。

    "dependencies": {
      "left-pad": "^1.1.3"
    }

    Now the project recognizes the left-pad dependency as existing

    You can also run npm install --save-dev to specify that the dependency will only be used for development (not production) purposes.

    卸载模块

    我们可以使用以下命令来卸载 Node.js 模块。

    $ npm uninstall express

    卸载后,你可以到 /node_modules/ 目录下查看包是否还存在,或者使用以下命令查看:

    $ npm ls

     

    更新模块

    我们可以使用以下命令更新模块:

    $ npm update express

    搜索模块

    使用以下来搜索模块:

    $ npm search express

    创建模块和发布模块

    创建模块使用的命令和步骤在前面npm init中己提到。

    使用以下命令在 npm 资源库中注册用户(使用邮箱注册):

    $ npm adduser Username: tielemao
    Password:  
    Email:  (this IS public)tieleyumao@gmail.com

    用以下命令来发布模块:

    $ npm publish

    如果你以上的步骤都操作正确,你就可以跟其他模块一样使用 npm 来安装自己发布的模块。

    版本号

    使用NPM下载和发布代码时都会接触到版本号。NPM使用语义版本号来管理代码,这里简单介绍一下。

    语义版本号分为X.Y.Z三位,分别代表主版本号、次版本号和补丁版本号。当代码变更时,版本号按以下原则更新。

    • 如果只是修复bug,需要更新Z位。
    • 如果是新增了功能,但是向下兼容,需要更新Y位。
    • 如果有大变动,向下不兼容,需要更新X位。

    版本号有了这个保证后,在申明第三方包依赖时,除了可依赖于一个固定版本号外,还可依赖于某个范围的版本号。例如"argv": "0.0.x"表示依赖于0.0.x系列的最新版argv。

    NPM支持的所有版本号范围指定方式可以查看官方文档

    使用淘宝 NPM 镜像

    大家都知道国内直接使用 npm 的官方镜像是非常慢的,这里推荐使用淘宝 NPM 镜像。

    淘宝 NPM 镜像是一个完整 npmjs.org 镜像,可以用此代替官方版本(只读),同步频率目前为 10分钟一次,以保证尽量与官方服务同步。

    使用淘宝定制的 cnpm (gzip 压缩支持) 命令行工具代替默认的 npm:

    $ npm install -g cnpm --registry=https://registry.npm.taobao.org

    这样就可以使用 cnpm 命令来安装模块了:

    $ cnpm install [name]

    Run Node in the terminal

    Let's create index.js in the root of our directory. This is everything you should have now:

    For future reference, don't bother looking in the node_modules rabbit hole. It will get really overwhelming with bigger projects.

    In order to use a dependency, we use require() and put it in a variable, like so:

    const leftPad = require('left-pad')

    This will be the entirety of our index.js file, in which we require left-pad, run a leftPad()function, and send it to the console.

    const leftPad = require('left-pad') // Require left pad
    const output = leftPad('Hello, World!', 15) // Define output
    
    // Send output to the console
    console.log(output)

    Since Node.js is not recognized by the browser, we'll be testing this in the console. In your shell, run the node command followed by the filename in the root of your project.

    node index.js

    If everything went well, you should have printed Hello, World! to the console, with two spaces on the left.

    Hello, World!

    Conclusion

    In this tutorial, we learned the following:

    • What Node.js is
      • 由于Node.js平台是在后端运行JavaScript代码,所以,必须首先在本机安装Node环境。
        • 在Windows上安装时务必选择全部组件,包括勾选Add to Path
        • node.js是javascript的一种运行环境,是服务器端的javascript的解释器。
      • Node.js是一个基于Chrome JavaScript运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。
      • Node.js 使用事件驱动, 非阻塞I/O模型而得以轻量和高效,非常适合在分布式设备上运行数据密集型的实时应用。
        • Node.js很适合搭建轻量的服务器(应用),所以它又被人称为服务器语言,前端中的后端语言。
    • What npm is
      • npm其实是Node.js的包管理工具(package manager)
        • 为啥我们需要一个包管理工具呢?因为我们在Node.js上开发时,会用到很多别人写的JavaScript代码。如果我们要使用别人写的某个包,每次都根据名称搜索一下官方网站,下载代码,解压,再使用,非常繁琐。于是一个集中管理的工具应运而生:大家都把自己开发的模块打包后放到npm官网上,如果要使用,直接通过npm安装就可以直接用,不用管代码存在哪,应该从哪下载。
        • 更重要的是,如果我们要使用模块A,而模块A又依赖于模块B,模块B又依赖于模块X和模块Y,npm可以根据依赖关系,把所有依赖的包都下载下来并管理起来。否则,靠我们自己手动管理,肯定既麻烦又容易出错
        • npm则是包含在node.js里面的一个包管理工具,就如同linux中的yum仓库,rpm包管理;如同python中的pip包管理工具一样。而这些包管理工具都是予以使用的人们方便,同时解决各种包依赖之间的关系的。
          • 既然npm是包管理工具,那么它自己也和node.js分开自成一个网站,在npm的网站上面,就如同github,其仓库中保管了N多的开源项目,有世界上众多开发者提供的项目。我们只需要在npm的网站上搜索相关的就可以找到,然后在线上下载也行,直接在自己的项目中使用命令行安装也行。
        • npm 由三个独立的部分组成:

          • npm官方网站(仓库源):网站 是开发者查找包(package)、设置参数以及管理 npm 使用体验的主要途径。
          • 注册表(registry)(package.json):注册表 是一个巨大的数据库,保存了每个包(package)的信息。
          • 命令行工具 (CLI):CLI 通过命令行或终端运行。开发者通过 CLI 与 npm 打交道。
      • npm已经在Node.js安装的时候顺带装好了
        • C:>npm -v
        • 不过若是想要单独更新npm时怎么办?可以使用以下两个命令进行更新:
          • npm install npm@latest -g 
          • npm install npm@next -g
    • How to install Node.js and npm on Windows or Mac
    • How to make a local project
    • How to install a dependency with npm
    • How to run a file using a node_modules dependency in a shell

    If you got lost at any point, view the source on GitHub.

    With this knowledge, you're ready to start using Gulp, Grunt, Webpack, Browserify, or anything else that depends on Node.js or npm.

    相关知识点

    前端的构建工具常见的有Grunt、Gulp、Webpack三种,Grunt比较老旧,功能少,更新少,插件少。

    Grunt和所有grunt插件都是基于nodejs来运行的,如果你的电脑上没有nodejs,就去安装吧。

    前端工程自动化方案更新很快, 学习这些工具,是为了减轻重复劳动,提高效率。选择适合自己的方案,而不是在追寻技术的路上迷失了方向。

     Gulp,

    gulp是一个自动化构建工具,主要用来设定程序自动处理静态资源的工作。简单的说,gulp就是用来打包项目的。

    gulp是基于Nodejs的自动任务运行器,它能自动化地完成javascript/sass/less/html/image/css 等文件的的测试、检查、合并、压缩、格式化、浏览器自动刷新、部署文件生成,并监听文件在改动后重复指定的这些步骤。

    使用Gulp的优势就是利用流的方式进行文件的处理,使用管道(pipe)思想,前一级的输出,直接变成后一级的输入,通过管道将多个任务和操作连接起来,因此只有一次I/O的过程,流程更清晰,更纯粹。Gulp去除了中间文件,只将最后的输出写入磁盘,整个过程因此变得更快。

    使用Gulp,可以避免浏览器缓存机制,性能优化(文件合并,减少http请求;文件压缩)以及效率提升(自动添加CSS3前缀;代码分析检查)

    gulp的插件使用

      同Grunt一般,gulp也有插件库,具体有兴趣开发gulp插件的,可以看看 http://www.gulpjs.com.cn/docs/writing-a-plugin/

     Grunt,

    前端自动化小工具,基于任务的命令行构建工具

    自备node环境(>0.8.0), npm包管理

    一般需要在你的项目中添加两份文件:package.json 和 Gruntfile

    Grunt的基本使用也就如上所示,比较简单,更多可以参考Grunt的插件库,比如 contrib-jshint js代码检查等插件的使用

    Webpack,

    Webpack是一个模块打包的工具,它的作用是把互相依赖的模块处理成静态资源。

    webpack的进阶使用 之 加载器

    何谓加载器?加载器是对你的应用的源文件进行转换的工具。

    不同类型的文件有不同的加载器,比如jsx,es6要用到babel-loader,

    加载css要用到css-loader,加载html要用到html-loader,以及 vue-loader,css-loader 等等. 

    所有的loader都放在module下面的loaders里边.通常有以下内容:

    1. test:是对该类文件的正则表达式,用来判断采用这个loader的条件 

    2. exclude是排除的目录,比如node_modules中的文件,通常都是编译好的js,可以直接加载,因此为了优化打包速度,可以排除。作为优化手段它不是必须的 

    3. loader: 加载器的名称,每一个加载器都有属于它自己的用法,具体要参考官方说明

    4. query: 传递给加载器的附加参数或配置信息,有些也可以通过在根目录下生成特殊的文件来单独配置,比如.babelrc 

      以上只是稍微讲了webpack的基础使用,更多使用方法 可以查看官方文档

    Browserify

     一个前端构建工具,只能构建JavaScript文件。

    可以让你使用类似于 node 的 require() 的方式来组织浏览器端的Javascript代码,通过预编译让前端Javascript可以直接使用 Node NPM 安装的一些库。

    Browserify是一个供浏览器环境使用的模块打包工具,像在node环境一样,也是通过require('modules')来组织模块之间的引用和依赖,既可以引用npm中的模块,也可以引用自己写的模块,然后打包成js文件,再在页面中通过<script>标签加载。

  • 相关阅读:
    库函数(汇总)
    IE jQuery ajax 请求缓存问题
    Jarvis OJ-level3
    在64位的linux中运行32位的应用程序
    ROP之linux_x64知识杂记
    2017年网络空间安全技术大赛部分writeup
    Sniper OJ部分writeup
    gdb插件使用方法
    pwntools学习
    linux虚拟机安装值得注意的几点
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/11758529.html
Copyright © 2011-2022 走看看