美文网首页
Node.js安装与nmp的基本使用

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

作者: playman | 来源:发表于2018-06-24 22:01 被阅读0次

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

相关文章

网友评论

      本文标题:Node.js安装与nmp的基本使用

      本文链接:https://www.haomeiwen.com/subject/wxnsyftx.html