node

106 阅读6分钟

node

一.认识node.js

  • Node.js是一个开源,跨平台的javaScript运行时环境
  1. 运行时环境

    • 浏览器,最早认识HTML CSS,后续谷歌推出V8引擎,提供识别js的能力
    • node:基于谷歌V8引擎,给我们提供了一个js 的运行时环境
    • node选择了js,而不是jf选择了node
  • node.js 和浏览器的差别1

    • BOM+DOM+ES

      • BOM: 浏览器提供的能力
      • DOM:html提供的能力
      • ES:js语言的一个规范
    • node.js

      • 运行js时,直接运行

        • 不需要放在html中,所以没有DOM
        • 直接在系统中运行,BOM也就没有了
        • 只剩下ES规范
    • node.js和浏览器的差别2

      • 浏览器

        • 可以有模块化开发,可以用非模块化
        • 非模块,就是所有的js引入到某一个html,此时所有的js文件公用一个window
      • node.js

        • 必须是模块化开发CommonJS 模块化语法,不能写ES6,模块化语法
        • 除了,模块化语法,其他的ES6新特性都支持
    • js代码没有错误的

      • 如果你的代码将来运行到浏览器中,那么可以书写DOM或者BOM

      • 如果你的代码将来运行node.js中,那么不能书写DOM或者BOM

        • 操作文件/文件夹
        • 操作电脑系统
        • 操作数据库

二.命令行的操作

  1. 命令行的操作: 仅仅是为了满足运行node

    1. windoow:cmd
    2. MAC:终端
  • cmd打开方式1

    • window+R
    • 输入cmd按下回车键
    • 打开的路径默认是系统路径
  • cmd打开方式2

    • 找到对应文件所在文件夹
    • 在文件夹路径上单击一个,输入cmd敲回车
  • 命令行常用操作

    • 返回上一级:输入命令:cd..
  • 查询当前目录内的子目录

    • 输入命令:dir
  • 进入对应目录

    • 输入命令: cd 文件夹名字
  • 清屏:

    • 输入命令: cls clear

三.利用node执行js代码

  1. 方式1

    1. 打开cmd,目录无所谓

    2. 输入命令node直接敲回车

    3. 进入一个线程,相当于浏览器控制台,我们可以在内部书写js代码

      1. 缺点:

        1. 没提示
        2. 书写代码,没办法保存

    2.将需要运行的js代码书写在 js 文件内

    • 打开cmd,目录需要在这个js文件的目录
    • 输入命令node文件名G:\JavaScript_2\week7\day2\02代码\01利用node书写js代码.js G:\JavaScript_2\week7\day2\02代码\03nodejs的模块化.js

四.nodejs的模块化

所有的东西,都是模块

  • node模块的分类

    • 自定义模块 : 自己写的
    • 内置模块 : nodejs提供的模块
    • 第三方模块 : 别人写好的对象,上传到某一个位置(npm),我们去npm下载到本地,然后使用
  • 导出 : node中每一个js文件都自带一个module(module是一个对象)

    • 导出语法1:module.exports.属性名 = 属性值
    • 导出语法2:module.exports = 新值(可修改,必须使用的方法)
    • 导出语法3:exports.属性名 = 属性值
  • node中每一个js文件都自带一个exports 这个变量内部存储,指向module.exports这个对象的地址

  • 导入: node中每一个js文件都自带一个require

    • 语法:require("地址')
    • 返回值: 返回这个导入文件的exports这个
// console.log(module)
/*
    Module {
        id: '.',
        // 当前文件所在目录
        path: 'C:\Users\41099\Desktop\GY-2203\07周\02天\code',
        // 记录了, 当前文件 导出的内容
        exports: {},
        // 当前文件完整的 文件名
        filename: 'C:\Users\41099\Desktop\GY-2203\07周\02天\code\04_nodejs的模块化.js',
        // 是否被引入
        loaded: false,
        // 表明当前文件 导入了 什么模块
        children: [],
​
        paths: [
            'C:\Users\41099\Desktop\GY-2203\07周\02天\code\node_modules',
            'C:\Users\41099\Desktop\GY-2203\07周\02天\node_modules',
            'C:\Users\41099\Desktop\GY-2203\07周\node_modules',
            'C:\Users\41099\Desktop\GY-2203\node_modules',
            'C:\Users\41099\Desktop\node_modules',
            'C:\Users\41099\node_modules',
            'C:\Users\node_modules',
            'C:\node_modules'
        ]
    }
*/

五.node内置模块fs

node 给我们提供的操作文件/文件夹的能力

0.  导入
0.  按照规则使用
  • 异步读取文件

    • fs.readFile('文件路径', '配置项', '回调函数')

      • 文件路径:必传
      • 配置项:选填(默认值buffer,可以手动设置(utf-8))
      • 回调函数:必填
    const fs = require('fs')
    console.log('start')
    fs.readFile('./index.txt', 'utf-8', function (err, data) {
        /**
         *  err: 如果读取失败, 会给一个 err
         *  data: 读取成功,文件的内容
        */
        if (err) return console.log(err)
        console.log(data)
    })
    console.log('end')
    // 打印结果
    // start
    // end
    // hello~~~
    
  • 同步读取文件

    const fs = require('fs')
    console.log('start')
    let data = fs.readFileSync('./index.txt', 'utf-8')
    console.log(data)
    console.log('end')
    // 打印结果
    // start
    // hello~~~
    // end
    
  • 异步写入

    • 按照指定第一个参数去书写文件内容(覆盖)
    • 按照指定的第一个参数没找到,在指定位置,新建一个文件出来,就是第二参数
    const fs = require('fs')
    console.log('start')
    fs.writeFile('./index123.txt', '你好', function (data) {
        console.log('写入完成')
    })
    ​
    console.log('end')
    // 打印结果
    // start
    // end
    // 写入完成
    

六.node内置模块path

  • node给我们提供的操作路径相关的内容

    • 导入
    • 按照规则使用
  • 绝对路径

    • C:/a/b/c/d.html
  • 相对路径

    • ./d.html
    • ../b/d.html
const path = require("path");
// console.log(path)
​
// path.join([路径片段1, 路径片段2, 路径片段3])
const res = path.join("a", "/b", "/c", "/d.html");
// console.log(res); // a\b\c\d.html
​
const res1 = path.resolve("a", "/b", "/c", "/d.html");
const res2 = path.resolve("q/w/e", "y.html");
// console.log(res1); // C:\d.html
// console.log(res2); // C:\Users\41099\Desktop\dfg\zdfg\02天\code\06_node内置模块path\h\w\e\y.html
​
const res3 = path.parse(
    'C:/Users/41099/Desktop/GY-2203/07周/02天/code/06_node内置模块path/q/w/e/y.html'
)
console.log(res3)
​
/*
​
    {
        // 根路径
        root: 'C:/',
        // 当前文件所在的文件夹(目录)路径
        dir: 'C:/Users/41099/Deskgfctop/dgferg/01/02天/code/06_node内置模块path/h/w/e',
        // 完整文件名
        base: 'y.html',
        // 文件后缀
        ext: '.html',
        // 文件名
        name: 'y'
    }
​
*/

七.node内置模块url

const url = require("url");
// console.log(url);
​
// url.parse('url 地址(必填)', '是否深度解析(选填, 默认为 false)')
const res = url.parse("http://localhost:8080/a/b/c/d.html?current=1&pagesize=12");
// console.log(res)
/*
    Url {
        // 协议
        protocol: 'http:',
        slashes: true,
        auth: null,
        // 域(域名+端口号)
        host: 'localhost:8080',
        // 端口号
        port: '8080',
        // 域名
        hostname: 'localhost',
        // hash值
        hash: null,
        // 携带的参数
        search: '?current=1&pagesize=12',
        // 查询字符串
        query: 'current=1&pagesize=12',
        // 完整路径名
        pathname: '/a/b/c/d.html',
        // 路径(带参数)
        path: '/a/b/c/d.html?current=1&pagesize=12',
        // 完整 url 路径
        href: 'http://localhost:8080/a/b/c/d.html?current=1&pagesize=12'
    }
*/
​
​
const res1 = url.parse("http://localhost:8080/a/b/c/d.html?current=1&pagesize=12", true);
console.log(res1)
/*
    Url {
        ...
        query: [Object: null prototype] { current: '1', pagesize: '12' },
        ...
    }
*/

八.内置模块 http

  • node给我们提供的开启一个服务器

  • 服务器: 一个提供服务的机器

    • 服务:数据或文件
    • 机器: 就是一台电脑
  • req:表明前端的请求报文

  • res:后端返回给前端的响应报文

// 0. 导入内置模块
const http = require("http");
​
// console.log(http);// 1. 创建一个 服务器
const server = http.createServer(function (req, res) {
    /**
     *  req: 表明前端的请求报文
     *  res: 后端返回给前端的响应报文
    */
​
    console.log(req.url)
    // console.log('每当有一个 前端 访问的时候, 我就会被触发一次')
​
    if (req.url == '/a') {
        res.end('hello~~~pageA')
    }
​
    if (req.url == '/b') {
        res.end('hello~~~pageB')
    }
​
})
​
// 2. 给服务器 配置一个 端口号(0~65535)
server.listen(8080, () => {
    console.log('服务器开启成功, 端口号 8080')
})