Node.js安裝與nmp的基本使用
JavaScript引擎
Browser,Headless Browser,or Runtime | JavaScript Engine |
---|---|
Mozilla | Spidermonkey |
Chrome | V8 |
Safari | JavaScriptCore |
IE and Edge | Chakra |
PhantomJS | JavaScriptCore |
HTMLUnit | Rhino |
TrifileJS | V8 |
Node.js | V8 |
Io.js | V8 |
chrome的V8引擎
初識Node.js
npm(Node Package Manager)
特點
- Node.js內置的包管理工具
- 收錄大量的開源工具
- 社群穩定
- 生態發達
npm的使用方法
- 安裝node.js 后系統會自動安裝npm
- npm -v 查詢版本
- npm init 新建工程項目
- npm install 安裝包
- npm update更新模塊
- 常用命令列表...
初始化 init命令
$ npm init
name: (0213)名稱
version: (1.0.0)版本號
description:描述
entry point: (index.js)入口點
test command:測試命令
git repository:git的倉庫
keywords:關鍵詞
author: 作者
license: (ISC)開源證書
安裝庫 install命令
$ npm install jquery --save
刪除 uninstall
$ nmp uninstall jquery --save
安裝低版本 @接版本號
$ npm install jquery@2 --save
安裝的另一種寫法 --save位置不同
$ npm install --save bootstrap
在刪除node_modules文件夾后,只要json文件在,直接執行install命令
$ npm install
更新
$ npm update jquery
更換源,換成淘寶的NPM鏡像
官網
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
Node.js使用
- Node.js需要借助命令行界面運行
- REPL程序
- 啟動外部代碼文件
node命令直接啟動
$ node
> 輸入內容
模塊怎么用?
- Node.js中也有全局對象的概念
- exports對象
- require對象
基本用法
cal.js
exports.add = function(x, y) {
return x+y;
}
exports.minus = function (x, y) {
return x-y;
}
index.js
var cal = require('./cal.js');
console.log(cal.add(5,6));
運行
$ node index.js
11
module.exports在模塊中只能寫一次,后面的會覆蓋。什么對象都能導出
hello.js
//定義原型函數
function Hello() {
this.name = 'hello func';
this.version = '1.0';
}
//添加方法
Hello.prototype = {
say:function() {
console.log(this.name);
}
}
//module拋出,這個只能寫一次
module.exports = Hello;
index.js
//加載
var hello = require('./cal.js');
//創建
var a = new hello();
//調用
a.say();
運行
$ node index.js
hello func
應用場景,如配置文件
//只拋一次,全都可以用
var config = {
username:"root",
password:"root"
}
module.exports = config;
搭建服務器(注意:這種方式不是每個瀏覽器都能正常查看)
index.js
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
response.end('<h1>Hello Server</h1>');
});
server.listen(4000, function () {
console.log('server is running at 4000');
});
命令行
$ node index.js
server is running at 4000