Node.js安裝與nmp的基本使用

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
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 概要 64學時 3.5學分 章節安排 電子商務網站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,298評論 0 3
  • Node.js是目前非常火熱的技術,但是它的誕生經歷卻很奇特。 眾所周知,在Netscape設計出JavaScri...
    w_zhuan閱讀 3,639評論 2 41
  • JavaScript 模塊化編程 網站越來越復雜,js代碼、js文件也越來越多,會遇到什么問題? 命名沖突; 文件...
    magic_pill閱讀 1,466評論 0 1
  • 1 Webpack 1.1 概念簡介 1.1.1 WebPack是什么 1、一個打包工具 2、一個模塊加載工具 3...
    Kevin_Junbaozi閱讀 6,731評論 0 16
  • Node.js是目前非常火熱的技術,但是它的誕生經歷卻很奇特。 眾所周知,在Netscape設計出JavaScri...
    Myselfyan閱讀 4,094評論 2 58