话不多说先下载。 (npm是和node.js一起发布的,只要安装了node.js,npm也安装好了)
安装完以后,首先要做的当然是测试是否安装成功。按 win + r 打开 cmd命令提示符 输入 npm -v ,出现提示版本安装成功
npm -v3.10.10
如果你安装的是旧版本的 npm,可以很容易得通过 npm 命令来升级
npm install npm@latest -g
使用 npm 命令安装模块先在电脑上新建一个项目文件夹,在cmd上找到该文件夹
c:\users\filbert\desktop>cd app2
c:\users\filbert\desktop\app2>
初始化npm,npm init –yes
c:\users\filbert\desktop\app2>npm init --yes wrote to c:\users\filbert\desktop\app2\package.json: { "name": "app2", "version": "1.0.0", "description": "", "main": "app2.js", "scripts": { "test": "echo \"error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "isc"}
安装express框架,npm install express
c:\users\filbert\desktop\ch3>npm install express –save npm warn ch3@1.0.0 no description npm warn ch3@1.0.0 no repository field. + express@4.15.4 updated 1 package in 3.63s
在项目中要搭建一个node服务器,就要先新建一个js文件,如app2.js
const path = require('path');const express = require('express'); const app = new express();const port = 4000;//app.use(express.static('public')); app.get('/*', (req, res) => { /*const pathname = req.params['0']; if(!pathname) { res.sendfile(path.join(__dirname, 'index.html')); return; }*/ res.sendfile(path.join(__dirname+'/index.html')); });var server = app.listen(port, (error) => { if (error) { console.error(error); } else { console.info('==> listening on port %s. open up http://localhost:%s/ in your browser.', port, port); } });
当你要执行node.js搭建的服务器时,在cmd中输入 node app2.js
c:\users\filbert\desktop\app2>node app2.js ==> listening on port 4000. open up http://localhost:4000/ in your browser.
复制 http://localhost:4000/ 即可查看页面
以上就是关于使用npm的详细内容。
