首页 > 编程语言 >node

node

时间:2022-12-06 18:57:22浏览次数:34  
标签:node fs const log err path console

第一章、 node.js快捷键

1. cd切换目录 ../ 切换到上一级目录
2. 使用↑箭头 快速定位到上一次执行的命令
3. 使用tab键 快速的补全路径
4. 使用esc键 快速的清空当已经输入的命令
5. cls键 清空终端里面的内容 

第二章、fs文件模块

  1. fs.readFile()方法 读取指定文件内容

fs.readFile(path, [, options], callback)
参数1:必修参数,字符串,表示文件的路径。
参数2:可选参数,表示一什么编码格式来读取文件。
参数3:必选参数,文件读取完成后,通过回调函数拿到读取的。

// 导入fs模块
const fs = require('fs');
// 调用 fs.readeFile()方法读取文件
fs.readFile('./files/1.txt', 'utf8', function (err, dataStr) {
    // 打印失败的结果
    // 如果读取成功,则 err 的职位Null
    // 如果读取失败 则err的值为 错误对象 dataStr 的值为undefined
    console.log(err);
    console.log('----------');
    // 打印成功的结果 
    console.log(dataStr);
})

第三章. fs.writeFile()方法 写入文件

  1. fs.writeFile() 方法 向指定的文件中写入内容

fs.writeFile(file, data[,options],callback)
参数1:必选参数,需要指定一个文件路径的字符串,表示文件存放的路径。
参数2:必选参数,表示要写入的内容。
参数3:参数2:可选参数,表示一什么编码格式来读取文件,默认是UTF8。
参数4:必选参数,表示文件写入完成后的回调函数。

// 1.导入fs文件模块 
const fs = require("fs");
// 2.调用fs.writeFile()方法 写入文件的内容
fs.writeFile("./files/txt", 'ok', function (err) {
    // 如果文件写入成果则err 值为null
    // 如果文件写入失败 则err 的值等于一个错误对象
    // console.log(err);
    if (err) {
        return console.log('文件写入失败' + err.message);
    } else {
        console.log('文件写入成功');
    }
})
  1. 读写的按列
// 1.引入fs系统模块 
const fs = require("fs");
//2. 用 fs.readFile()方法读取文件的内容 
fs.readFile('./files/4.学生成绩.txt', 'utf8', function (err, dadaStr) {
 //3 判断文件是否读取成功 
 if (err) {
     return console.log('读取文件失败' + err.message);
 }
 // console.log('读取文件成功' + dadaStr);
 // 先把成绩的数据 按周空格分隔
 const oldArr = dadaStr.split(' ')
 // console.log(oldArr);
 // 循环分隔后的数组 对每一项数据进行字符串的替换操作
 const newArr = [];
 oldArr.forEach(function (value) {
     newArr.push(value.replace('=', ':'))
 })
 // console.log(newArr);
 // 把新的数组的没一项进行合并 的到一个姓的字符串
 const newStr = newArr.join('\r\n');
 console.log(newStr);

 // fs.writeFile() 抵用它写入成绩成功
 fs.writeFile('./files/5.写入.txt', newStr, function (err) {
     if (err) {
         return console.log('写入文件失败' + err.message)
     }
     console.log('成绩写入成功');
 })
})

第四章、 文件的路径(__dirname表示当前文件所存在的路径)

const fs = require("fs");
// 出现路径拼接错误的问题 是因为提供了 ./ 或者../ 开头的相对路径
// 如果解决这个问题 可以直接提供一个完整的文件存放的路径就可以
/* fs.readFile('./files/4.学生成绩.txt', 'utf8', function (err, data) {
    if (err) {
        return console.log('读取文件失败' + err.message);
    }
    console.log('读取文件成功' + data);
}) */


// 问题移值性非常的差  不利于维护
/* fs.readFile('C:\\Users\\默言\\Desktop\\node\\files\\1.txt', 'utf8', function (err, data) {
    if (err) {
        return console.log('读取文件失败' + err.message);
    }
    console.log('读取文件成功' + data);
}) */


// __dirname表示当前文件所处的目录
 fs.readFile(__dirname+'/files/1.txt', 'utf8', function (err, data) {
    if (err) {
        return console.log('读取文件失败' + err.message);
    }
    console.log('读取文件成功' + data);
}) 

第五章、 path.join路径拼接

path.join([..paths])
参数:返回的路径

const path = require("path");
const fs = require("fs");

// // 注意 ../会抵消前面的路径
// const str = path.join('/a', '/b/c', '../', './d', 'e');
// console.log(str);//\a\b\d\e
// fs.readFile(__dirname + '/files/1.txt')
fs.readFile(path.join(__dirname, '/files/1.txt'), 'utf8', function (err, dada) {
    if (err) {
        return console.log(err);
    }
    console.log(dada);
})
  1. path.basename()方法 获取文件名
const path = require("path");

// 定义文件存放的路径
const fPath = '/a/b/c/index.html/';
/* const fullname = path.basename(fPath);
console.log(fullname);//index.html
*/
// basename 获取文件的名称 
const name = path.basename(fPath, 'html')
console.log(name);//index
  1. path.extname()方法 获取文件后缀名
const path = require("path");
// extname 获取文件的后缀
const fPath = '/a/b/c/index.html';
const fext = path.extname(fPath);
console.log(fext);//.html
  1. 按列
// 导入fs  模块
const fs = require("fs");
// 导入path 模块
const path = require("path");

// 定义正则表达式 分别匹配<style></style>和<script></script>
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;

// 调用fs.readFile()读取文件 
fs.readFile(path.join(__dirname, './clock/index.html'), 'utf8', function (err, data) {
    if (err) {
        return console.log('读取HTML文件失败' + err.message)
    }
    console.log('文件写入成功' + data);
    // 读取文件成功后 调用对应的三个方法 分别拆解css js html文件
    resolveCSS(data);
    resolveJS(data);
    resolveHTML(data);
})

// 定义处理css 样式的方法 
function resolveCSS(htmlStr) {
    // 使用正则提取需要的内容
    const r1 = regStyle.exec(htmlStr);
    // 将提取出来的样式字符串 进行字符串的replace 替换操作
    const newCss = r1[0].replace('<style>', '').replace('</style>', '');
    // 调用 fs.writeFile()方法 将提取的样式 写到root目录中的index.css的文件里面
    fs.writeFile(path.join(__dirname, './root/index.css'), newCss, function (err) {
        if (err) return console.log('写入css样式失败');
        console.log('写入css样式文件成功');
    })
}

// 定义处理js脚本的方法
function resolveJS(htmlStr) {
    // 通过正则提取对应的js内容 
    const r2 = regScript.exec(htmlStr);
    // 将提出出来的内容进行处理 
    const newJS = r2[0].replace('<script>', '').replace('</script>', '');
    // 将处理的结果写入到 root 目录中的index.js文件里面
    fs.writeFile(path.join(__dirname, './root/index.js'), newJS, function (err) {
        if (err) return console.log('写入Js脚本文件失败');
        console.log('写入js脚本文件成功');
    })
}

// 定义处理HTML结构的方法 
function resolveHTML(htmlStr) {
    //  将字符床调用replace 方法 把内嵌的style和script替换为外联的link 和script标签
    const newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css"/>').replace(regScript, '<script src="index.js"></script>')
    //    写入index.html 这个文件 
    fs.writeFile(path.join(__dirname, "./root/index.html"), newHTML, function (err) {
        if (err) return console.log("写入HTML文件失败" + err.message);
        console.log('写入html页面成功');
    })
}

第六章、 http模块

1.导入http模块

const http=require('http');

  1. http.createSever()方法 可创建一个web服务器
    image

  2. request 为服务器绑定时间
    image
    image
    image

  3. listen启动服务器

// 1.导入http模块
const http = require("http");
// 2.创建外部服务器实例
const sever = http.createServer()
// 3.为服务器实例绑定request事件,监听客户端的请求
sever.on('request', function (req, res) { 
    console.log('Someone visit web sever');
})
// 4.启动服务器 80的端口可以省略
sever.listen(8080, function () {
    console.log('sever running at http://127.0.0.1:8080');
})


  1. 按列
// 1.导入 http模块
const http = require("http");

// 2.导入fs 模块
const fs = require("fs");

// 3.导入path模块
const path = require("path");

// 2.1 创建一个 web 服务器
const server = http.createServer();

// 2.2 监听web 服务器的request 事件
server.on('request', (req, res) => {
    // 3.1 获取到客户端请求 url 的地址
    const url = req.url;
    //  /root/index.html
    //  /root/index.css
    //  /root/index.js

    // 3.2 把请求的url 地m址映射为具体的文件的存放路径
    // const fPath = path.join(__dirname, url);

    // 定义一个空的文件路径
    let fPath = '';
    // 如果请求的路径是否为 / 则手动定义文件存放的路径
    if (url === '/') {
        fPath = path.join(__dirname, './root/index.html');
    } else {
        //  /root/index.html
        //  /root/index.css  
        //  /root/index.js
        // 请求路径不为  / 动态拼接文件存放的路径
        fPath = path.join(__dirname, './root', url)
    }

    // 4.1 根据映射过来的文件路径读取文件的内容
    fs.readFile(fPath, 'utf8', (err, data) => {
        // 4.2 文件读取失败 向客户端响应固定的错误的信息
        if (err) return res.end('404 Not found');

        // 4.3 读取成功 将数据响应给客户端
        res.end(data)
    })
})

// 2.3 启动服务器
server.listen(80, () => {
    console.log('sever running at http://127.0.0.1');
})




标签:node,fs,const,log,err,path,console
From: https://www.cnblogs.com/dexue/p/16959160.html

相关文章

  • ansible 清理k8s集群的node节点日志
    目录ansible清理k8s集群的node节点日志获取对应节点信息脚本删除各个节点的日志脚本ansible分发clear_docker_log.sh并做成计划任务ansible清理k8s集群的node节点日志......
  • 03.Nodejs中的路由与接口
    路由与接口目录目录路由与接口express基本使用托管静态资源nodemonExpress中的路由路由的匹配路由的使用模块化路由Express中间件中间件的格式全局生效的中间件局部生效......
  • 04.Nodejs操作MySQL
    在Nodejs中操作MySQL数据库目录在Nodejs中操作MySQL数据库MySQL数据库SQL的基本使用SELECT语句INSERTINTO语句UPDATE语句DELETE语句WHERE子句AND与OR运算符ORDERBY子......
  • 05.Nodejs_web开发模式
    Web开发目录目录Web开发Web开发模式服务端渲染的传统Web开发模式前后端分离的Web开发模式Session认证机制在项目中使用Session向session中存入数据:从session中获取数......
  • 00.Nodejs环境搭建
    Nodejs的环境搭建目录Nodejs的环境搭建安装node搭建服务器环境查看本地ip项目复活安装node英文官网:https://nodejs.org/en/中文官网下载node地址https://nodejs.or......
  • 在Node.JS中调用JShaman接口,实现JS代码加密
    在Node.JS中调用JShaman接口,实现JS代码加密。使用axios库实现https的post请求,代码如下:constaxios=require("axios");constjshamanConfig={//源码"js_code":......
  • Ubuntu 14.04 iNode Client找不到库libjpeg和libtiff的解决方法
    iNodeClient在Ubuntu10.04时,直接运行install.sh后便安装成功。在Ubuntu14.04的版本,安装后双击iNodeClient后却无法运行。重装后问题依旧。于是使用命令行来运行。提示......
  • warn]: Component inside <Transition> renders non-element root node that cannot b
    因为比较简单先说解决方法:用一个div把过渡到的代码(组件代码)包起来即可详情:用到transition: (提升用户体验组件动画)警告信息:过渡的组件代码:解决:(用d......
  • win7安装高版本node
    原文链接:https://www.ngui.cc/article/show-584755.htmlexecjs库只支持nodejs14.0.0以上的版本,win7最高只支持node13.14.0版本nvmw:Windowsnodejs版本......
  • 项目坑 | Node 版本的切换
    8.0.0Node问题 版本不对 旧的terminal换成8.17.0 ==> 8.17.0不是全局==》npm不是6版本 原先terminal......