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,368评论 0 3
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    w_zhuan阅读 3,643评论 2 41
  • JavaScript 模块化编程 网站越来越复杂,js代码、js文件也越来越多,会遇到什么问题? 命名冲突; 文件...
    magic_pill阅读 1,492评论 0 1
  • 1 Webpack 1.1 概念简介 1.1.1 WebPack是什么 1、一个打包工具 2、一个模块加载工具 3...
    Kevin_Junbaozi阅读 6,789评论 0 16
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    Myselfyan阅读 4,105评论 2 58