hello world
创建app.js, 运行node app.js
const http = require('http');
http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('hello world');
}).listen(3000);
console.log("server running...");
Node.js - REPL
REPL可以 读取,打印,计算,循环。相当于浏览器的控制台。常用命令:ctrl+c .help
C:\1_dev\giteeRepository\yards\nodeTest> node
Welcome to Node.js v14.15.0.
Type ".help" for more information.
>
Node.js - npm
npm为Node的包管理工具,相当于maven,远程仓库为search.nodejs.org。v0.6.3后node捆绑安装,不用另行下载。
安装
搜索npm search
更新npm update
卸载npm uninstall cowsay
本地安装npm install abc
全局安装npm install -g abc
指定版本npm install abc@1.0
查看最新版本npm view abc version
程序中发觉最新版本npm outdated
install与install -D
install时会添加到Package.json的dependencies(生产环境)中,而添加-D会添加到devDenpendencies(开发环境)中
母牛说话小程序: 先后执行
npm install -g cowsay
npx cowsay helloworld/npx cowthink helloworld
Package.json 属性
version 表明了当前的版本。
name 设置了应用程序/软件包的名称。
description 是应用程序/软件包的简短描述。
main 设置了应用程序的入口点。
private 如果设置为 true,则可以防止应用程序/软件包被意外地发布到 npm。
scripts 定义了一组可以运行的 node 脚本。
dependencies 设置了作为依赖安装的 npm 软件包的列表。
devDependencies 设置了作为开发依赖安装的 npm 软件包的列表。
engines 设置了此软件包/应用程序在哪个版本的 Node.js 上运行。
browserslist 用于告知要支持哪些浏览器(及其版本)。
package-lock.json
用于锁定安装时的包版本,以便他人使用时保持依赖版本的一致性,需要上传到github
事件触发器
const EventEmitter = require('events');
const event = new EventEmitter();
event.on('test', ()=>{
console.log('hello emitter');
})
event.emit('test');