Node.js-简介/文件模块/path模块/http模块


浏览器中的javascript的组成部分

浏览器中的javascript的运行环境

总结:V8引擎负责解析和执行js代码 内置API是由运行环境提供的特殊接口,只能在所述的运行环境中被调用。   node.js是一个后端运行环境,js可以在node中进行后端开发。  

Node.js简介

一个基于谷歌V8引擎的js运行环境 注意:
  1. 浏览器是js的前端运行环境
  2. Node.js是js的后端运行环境
  3. Node.js中无法调用DOM和BOM等浏览器内置API  
Node.js的作用 提供一些基础的功能和API 基于Express框架,可以快速构建web应用 基于Electron框架,可以构建跨平台的桌面应该 基于restify框架,可以快速构建API接口项目 读写和操作数据库、创建使用的命令行工具辅助前端开发等   安装Node.js之后,在终端输入node -v查看版本号

fs文件系统模块

读取指定文件中的内容

创建两个js文件 然后在test.js中写入测试内容 在上一个js文件中写入如下
//1.导入fs模块 来操作
const fs = require('fs');
//2.调用fs.readfile()方法读取文件
fs.readFile("test.js", 'utf-8', function (err, datastr) {
    //2.1打印失败
    console.log(err);
    console.log("--------");
    //3.打印成功代码
    console.log(datastr);
})

之后在终端上进行测试

shuchenhao@shuchenhaodeMacBook-Air Node % node 使用readfile方法读取.js  null -------- console.log("hello node.js sss");  

当读取不到文件时

shuchenhao@shuchenhaodeMacBook-Air Node % node 使用readfile方法读取.js [Error: ENOENT: no such file or directory, open 't.js'] {   errno: -2,   code: 'ENOENT',   syscall: 'open',   path: 't.js' } -------- undefined  

判断err对象是否为null,从而判断文件是否读取成功

 
const fs = require('fs');
fs.readFile('1.js', 'utf-8', function (err, datastr) {
    if (err) {
        return console.log('读取文件失败' + err.message);
    }
    console.log('读取文件成功' + datastr);
})

终端测试

shuchenhao@shuchenhaodeMacBook-Air Node % node 判断文件是否读取成功.js  读取文件成功console.log("hello node.js sss"); shuchenhao@shuchenhaodeMacBook-Air Node % node 判断文件是否读取成功.js 读取文件失败ENOENT: no such file or directory, open '1.js'  

写入内容

 
//1.导入fs文件系统模块
const fs = require('fs');
//2.写入内容
fs.writeFile('testwrite.js', '测试写入情况', function (err) {
    console.log(err);

})
如果写入成功,则输出err=null 如果写入失败,则输出err等于对象 终端测试结果 shuchenhao@shuchenhaodeMacBook-Air Node % node 文件写入内容.js null   输出文件

判断是否写入成功

//1.导入fs文件系统模块
const fs = require('fs');
//2.写入内容
fs.writeFile('testwrite.js', '测试写入情况', function (err) {
    if (err) {
        return console.log("文件写入失败" + err.message);
    }
    console.log("文件写入成功");

})
终端测试结果 shuchenhao@shuchenhaodeMacBook-Air Node % node 文件写入内容.js  文件写入成功   练习:考试成绩管理 核心实现步骤
  1. 导入需要的fs文件系统模块
  2. 使用读取文件方法,读取素材目录下的成绩.txt
  3. 判断改文件是否读取成功
  4. 文件读取成功之后,处理成绩数据
  5. 将处理完程度额成绩数据,调用写入方法,写入到新文件中
//1.导入fs
const fs = require('fs');
//2.调用读取
fs.readFile('grade.txt', 'utf-8', function (err, datastr) {
    //3.判断
    if (err) {
        return console.log('读取失败' + err.message);
    }
    // console.log('读取成功' + datastr);

    //(1)先把成绩数据,按照空格进行分割
    const arrold = datastr.split(' ');
    //(2)循环分割后的数组,对每一项数据进行字符串替换操作
    const arrnew = [];
    arrold.forEach(item => {
        arrnew.push(item.replace('=', ':'))
    })
    //(3)把新数组中的每一项,进行合并,得到哦一个新数组
    const newstr = arrnew.join('\r\n');
    console.log(newstr);
    //5.写入
    fs.writeFile('grade-new.txt', newstr, function (err) {
        if (err) {
            return console.log('写入失败' + err.message);
        }
        console.log('写入成功');
    })
})
测试结果 shuchenhao@shuchenhaodeMacBook-Air Node % node 整理成绩.js 小红:88 小明:99 小花:98 小刚:97 小刘:96 写入成功  

 路径动态拼接的问题

在使用fs模块操作文件时,如果提供的操作路径以./或../开头的相对路径时,很容易出现路径动态拼接 错误的问题。 原因:代码在运行的时候,会以执行node命令时所处的目录,动态拼接出被操作文件的完整路径 解决方案:解决路径拼接错误问题,可以直接提供以一个完整的存放路径
const fs = require('fs');
fs.readFile(__dirname + "/test.js", 'utf-8', function (err, datastr) {
    if (err) {
        return console.log('读取失败' + err.message);
    }
    console.log('读取成功' + datastr);
})

path路径模块

用来处理路径模块 1.路径拼接
//注意:  ../会抵消前面的路径
const pathstr = path.join('/a', '/b/c', '../../', './d', 'e');
console.log(pathstr);
//测试
fs.readFile(path.join(__dirname, '/test.js'), 'utf-8', function (err, datastr) {
    if (err) {
        return console.log(err.message);
    }
    console.log(datastr);
})

2.获取路径中的文件名

//定义文件的存放路径
const fpath = '/a/b/c/index.html';
const fullname = path.basename(fpath);
console.log(fullname);
//不希望拿到扩展名
const namewithoutext = path.basename(fpath, '.html')
console.log(namewithoutext);

3.获取路径中的文件扩展名

const fpath = '/a/b/c/index.html';
const fext = path.extname(fpath);
console.log(fext);

案例:将一个index文件中的style标签和script标签拆分为单独文件,然后链接引入

//导入fs模块,path模块
const fs = require('fs');
const path = require('path');
//定义正则
const regstyle = /', '');
    fs.writeFile(path.join(__dirname + '/anli/index.css'), newCSS, function (err) {
        if (err) {
            return console.log('写入失败' + err.message);
        }
        console.log('写入成功');
    })

}
function resolveJS(htmlstr) {
    const r2 = regscript.exec(htmlstr);
    const newJS = r2[0].replace('', '');
    fs.writeFile(path.join(__dirname + '/anli/index.js'), newJS, function (err) {
        if (err) {
            return console.log('写入失败' + err.message);
        }
        console.log('写入成功');
    })
};
function resolveHTML(htmlstr) {
    const newHTML = htmlstr.replace(regstyle, ' ').replace(regscript, '');
    fs.writeFile(path.join(__dirname + '/anli/index.html'), newHTML, function (err) {
        if (err) {
            return console.log('写入失败' + err.message);
        }
        console.log('写入成功');

    })
};
注意点:
  • fs.writeFile()方法只能用来创建文件,不能用来创建路径
  • 重复调用fs.writeFile()写入用一个文件,新写入的内容会覆盖之前的内容

http模块

创建web服务器的模块 创建基本的web服务器
//1.导入http模块
const http = require('http');
//2.创建web服务器实例
const server = http.createServer();
//3.为服务器实例绑定request事件,监听客户端请求
server.on('request', function (req, res) {
    console.log('some visit our web server');
})
//4.启动服务器
server.listen(8080, function () {
    console.log('server running at http://127.0.0.1:8080');
})
在终端中运行该文件,显示结果如下 server running at localost   当在浏览器中输入http://127.0.0.1:8080 终端中显示 some visit our web server  

根据不同的URL响应不同的html内容

 
const http = require('http');
const server = http.createServer()
server.on('request', (req, res) => {
    const url = req.url;
    let content = '

404 not found!

'; if (url == '/' || url == '/index.html') { content = '

首页

'; } else if (url == '/about.html') { content = '

关于页面

'; } //防止中文乱码 res.setHeader('Content-Type', 'text/html;charset=utf-8'); //返回响应 res.end(content); }) server.listen(80, () => { console.log('server running at http://127.0.0.1'); })