Node.js 学习笔记

Node.js 学习笔记


一、Node.js 简介

  1. 是什么
    • 以前:JS代码写好了,写过HTML引入浏览器解析运行
    • 现在: JS代码写好了,直接通过Node软件解析运行即可

  • Node.js是JavaScript运行环境,可以解析JS代码
  1. 能干嘛
    • 作用:让Javascript成为与PHP,python平起平坐的语言
    • 前端脱离后端,直接通过JS写项目(接口、爬虫、桌面应用)

与JavaScript的区别

  • 基于异步I/O相关接口
  • 基于node_modules和require的模块依赖
  • 提供C++ addon API与系统交互

特性

  • 事件驱动
  • 单线程/异步/非阻塞
  • npm

使用Node.js进行爬虫

const puppeteer= require('puppeteer');
const url='https://movie.douban.com/subject/26931786/comments?sort=time&status=F';
(async ()=>{
 const browser=await puppeteer.launch();
 const page=await browser.newPage();
 await page.goto(url);
 const data=await page.evaluate(() => {
     return Array.from(document.querySelectorAll('.comment-item'),cmt => ({
        user: cmt.querySelector('.comment-info a').innerText,
        content: cmt.querySelector('p').innerText
     }));
 });
data.forEach(({user,content}) => console.log(`${user}:${content}`));
await browser.close();
})();

二、Node.js语法


1.数据类型

image-20220409185719205

2.对象

let obj ={
  a:1,
  b:{
    c:"hello",
    d:true
  }
};
console.log(obj.b.c);
let arr=[1,2,3];
console.log(arr.length);
console.log(arr.map(v => v*2));
typeof arr;

3.变量定义

  • var 可以重复定义
  • let 只允许定义一次
  • const 不可重新赋值

使用变量 需要$进行包裹

4.异步

setTimeout(function(){
  console.log('world');
},1000);
console.log('hello');
setTimeout(() => {
  console.log(1);
  setTimeout(() => {
    console.log(2)
  }, 1000);
}, 1000);

使用这种方式需要回调,所以考虑下面promise的方式:

const promise1=new Promise(function(resolve,reject){
  setTimeout(function(){resolve('foo')},300)
});
promise1.then((value)=>{
  console.log(value);
});

console.log(promise1)

const { resolve } = require("promise")

function timeout(time){
  return new Promise(function(resolve)
  {
    setTimeout(resolve,time);
  });
}
timeout(1000).then(function(){
  console.log(1);
}).then(function(){
  timeout(1000);
}).then(function(){
  console.log(2);
});
async function timeout(time)
{
  return new Promise(function(resolve){
    setTimeout(resolve,time);
  });
}
let main = async function() {
await timeout(1000);
console.log(1);
await timeout(1000);
console.log(2);}
main();

Promise对象代表一个异步操作,有三种状态:Pending(进行中)、Resolved(已完成 ,又称Fulfilled)和 Rejected(已失败)。

resolve(data)将这个promise标记为resolved,然后进行下一步then((data)=>{//do something}),resolve里的参数就是传入then的数据

执行到 resolve()这个方法的时候,就改变promise的状态为resolved,当状态为 resolved的时候就可以执行.then()

当执行到 reject() 这个方法的时候,就改变 promise的状态为 reject,当promise为reject就可以.catch()这个promise了

这两个方法可以带上参数,用于.then()或者 .catch() 中使用。他们的作用就是 用于改变promise的状态,因为状态改变了,所以才可以执行相应的.then()和 .catch()操作。

5. 函数

一般表示方式

function say(word) {
  console.log(word);
}

function execute(someFunction, value) {
  someFunction(value);
}

execute(say, "Hello");

匿名函数表示

function execute(someFunction, value) {
  someFunction(value);
}

execute(function(word){ console.log(word) }, "Hello");

HTTP例子:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

原型:

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

三、模块和npm


1.HTTP服务

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);
console.log('服务器运行中....')

2.模块

  • 内置模块:编译进Node中,例如http fs net process path等
  • 文件模块:原生模块之外的模块,和文件夹一一对应

自定义模块

const pi=Math.PI;
exports.area=function(r){
  return pi*r*r;
};
exports.circumference=function(r){
  return 2*pi*r;
};

image-20220410113649895

包依赖

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Nb1Q257o-1649570527127)(C:\Users\86180\AppData\Roaming\Typora\typora-user-images\image-20220410115738398.png)]

四、构建Web应用


1. koa模块


const Koa=require('koa')
const app =new Koa();
app.use(ctx=>{
  ctx.body='Hello Koa';
});
app.listen(3000);



const Koa=require('koa')
const app =new Koa();
app.use(async (ctx,next)=>{
  const start=Date.now();
  await next();
  const ms=Date.now()-start;
  console.log(`${ctx.method} ${ctx.url}-${ms}ms`)
});
app.use(ctx =>{
  ctx.body='hello koa';
});
app.listen(3000);

执行过程

image-20220410124351401

2.thinkjs

image-20220410124647001

3.TodoList 项目实战

API

  • 获取TOO 列表
  • 增加TODO
  • 删除TODO
  • 更新TODO状态

数据表设置

create  table `ticket`(
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`desc` varchar(255) not null default '',
`status` tinyint(11) not null default '0' comment '0 是未完成,1是已完成',
`createdAt` datetime not null default current_timestamp,
`updatedAt` datetime not null default current_timestamp on update current_times
primary key(`id)
)engine=innodb default charset=utf8mb4;

建立thinkjs 项目

  • npm install thinkjs

  • thinkjs new todo

  • cd todo

  • npm install

  • npm start

API

image-20220410132958232

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1fbf3jsI-1649570527129)(https://s2.loli.net/2022/04/10/XYgIAZCQq38tSfe.png)]

学习网址:

Web前端攻城狮 - 清华大学 - 学堂在线 (xuetangx.com)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值