Node.js安装与nmp的基本使用

2018-06-24  本文已影响0人  playman

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)

特点

npm的使用方法

初始化 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命令直接启动

$ node
> 输入内容

模块怎么用?

基本用法

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
上一篇 下一篇

猜你喜欢

热点阅读