Node.js - 基础与读写文件

什么是Node.js

Node.js的定义

  • Node.js 是一个基于 Chrome V8 引擎 的 JavaScript 运行时

Node.js环境与浏览器环境的区别

  • 在浏览器端:js由三部分组成:ECMAScript + BOM + DOM
  • 在NoeJS端:由ECMAScript + 内置模块(fs, http, path等) +第三方模块(别人开发的模块)
  • 注意:NodeJS中没有DOM,也没有BOM,也没有window对象。
  • 浏览器是JS的前端运行环境,Node.js是JS的后端运行环境

下载和安装 Node.js 环境

  • 注意:
    1.win10 可以随意安装任何版本的Node
    2.但是win7只能安装12及其以下的版本Node 以往版本下载

  • 点击下载到的安装包,一路下一步默认安装
    注意:
    1.不能安装到中文目录如d:/软件,建议一直点击next即可
    2.安装完成之后, 它不会在桌面出现快捷图标

  • 打开小黑窗输入 node -v 能看到版本号表示安装成功
    在任意文件夹中最上方的路径中输入cmd后回车即可打开
    在这里插入图片描述

常用命令

在这里插入图片描述

打开终端方法

List item
2. 快捷键 : ctrl + ~

核心模块

导入核心模块 - fs

// 导入核心模块  文件读写模块 fs 对象
const fs = require('fs');

console.log(fs);

fs模块 - 异步读取文件

// 引入核心模块
const fs = require('fs');

// 读取文件
fs.readFile('./txt/1.txt', 'utf8', (err, data) => {
    if (err) {
        console.log('==========');
        console.log('错误错误--------------');
        console.log('==========');
    } else {
        // 打印内容
        console.log('正常运行-----------------------');
        console.log(data);
    }
});

// 读取图片
fs.readFile('./images/1609683065082.jpg', (err, data) => {
    // 打印内容
    console.log(data);
});

fs模块 - 同步读取文件

// 引入核心模块
const fs = require('fs');

// try 里面放可能会出错的程序
// catch 捕获 try里面的程序出错了  catch会触发 里面做错误处理

try {
    // 开始同步读取文件
    const data = fs.readFileSync('./txt/1.txt', 'utf-8');
    console.log('-------------------------------------');
    console.log('同步读取文件');
    console.log(data);
    console.log('-------------------------------------');
} catch (err) {
    console.log('==================================================');
    console.log('发送邮件,错误处理');
    console.log(err);
    console.log('==================================================');
}

fs模块 - 异步写入内容

writeFile(‘路径’,‘内容’,‘utf8’,callback)
utf8可省略

const fs = require('fs');

// 写入内容  异步
fs.writeFile('./txt/2.txt', '丑八怪,别把灯打开', err => {
    //   err 有值:表示出错
    //   err 没有值,null:表示运行正常
    if (err) {
        console.log('===================================================');
        console.log('异步写入错误');
        console.log(err);
        console.log('===================================================');
    } else {
        console.log('---------------------------------------------------');
        console.log('异步写入成功');
        console.log('---------------------------------------------------');
    }
});

// 总结:
// 如果文件有内容再写入内容 会覆盖
// 如果路径没有文件再写入内容 会创建文件并写入内容

fs模块 - 同步写入内容

writeFileSync(‘路径’,‘内容’,‘utf8’)
utf8可省略

const fs = require('fs');

try {
    // 写入内容  同步
    fs.writeFileSync('./txt/1.txt', '如果邪恶是华丽残酷的乐章');

    console.log('----------------------------------------------------');
    console.log('同步写入成功');
    console.log('----------------------------------------------------');
} catch (err) {
    console.log('========================================================');
    console.log('同步写入失败');
    console.log(err);
    console.log('========================================================');
}

// 总结:
// 如果文件有内容再写入内容 会覆盖
// 如果路径没有文件再写入内容 会创建文件并写入内容

fs模块 - 同步追加内容

const fs = require('fs');

let index = 0;

while (true) {
    index++;
    fs.appendFileSync('./txt/1.txt', index + '-');
    console.log('追加成功', index);
}

// 死循环追加,记得 ctrl + c

// try {
//     // 追加内容  同步
//     fs.appendFileSync('./txt/1.txt', '如果邪恶是华丽残酷的乐章');

//     console.log('----------------------------------------------------');
//     console.log('同步追加成功');
//     console.log('----------------------------------------------------');
// } catch (err) {
//     console.log('========================================================');
//     console.log('同步追加失败');
//     console.log(err);
//     console.log('========================================================');
// }

fs模块 - 异步追加内容

const fs = require('fs');

// 写入内容  异步
fs.appendFile('./txt/1.txt', '丑八怪,别把灯打开', err => {
    //   err 有值:表示出错
    //   err 没有值,null:表示运行正常
    if (err) {
        console.log('===================================================');
        console.log('异步追加错误');
        console.log(err);
        console.log('===================================================');
    } else {
        console.log('---------------------------------------------------');
        console.log('异步追加成功');
        console.log('---------------------------------------------------');
    }
});

案例: 图片拷贝

  • . 需求: 执行js文件,读入到图片并写入到一个新的文件中显示
  1. 导入核心模块
  2. 读取到图片文件,注意不能添加 utf8,因为图片并不是文本格式
  3. 将读取到的图片写入新的文件中,不能添加utf8
const fs = require('fs');

// // 异步
// // 1.读取图片
// fs.readFile('./images/1.png', (err, data) => {
//     if (err) {
//         console.log('读取错误');
//     } else {
//         console.log('读取成功');

//         // 2.写入文件
//         fs.writeFile('./images/2.png', data, (err, data) => {
//             if (err) {
//                 console.log('写入错误');
//             } else {
//                 console.log('写入成功');
//             }
//         });
//     }
// });

// 同步
try {
    // 1.读取图片
    let file = fs.readFileSync('./images/1.png');
    console.log('读取成功');

    try {
        // 2.写入文件
        fs.writeFileSync('./images/3.png', file);
        console.log('写入成功');
    } catch (err) {
        console.log('写入失败');
    }
} catch (err) {
    console.log('读取失败');
}

案例:JSON格式添加内容

  • 需求:执行一次js文件,JSON文件中的数组就多添加一位 . 例如: [1,2] =>[1,2,3]
  1. 导入核心模块
  2. 读取JSON文件,读取到的内容都是字符串,所以要用JSON.parse转数组操作
  3. 用数组方法 push ,追加到数组中
  4. 再写入JSON文件中,需要先用JSON.stringify转成JSON字符串再写入文件中覆盖
const fs = require('fs');

// // 同步
// let files = JSON.parse(fs.readFileSync('./libs/1.json', 'utf8'));
// files.push(files.length + 1);
// // console.log(files);
// let data = fs.writeFileSync('./libs/1.json', JSON.stringify(files), 'utf8');
// console.log(data);

//异步
fs.readFile('./libs/1.json', 'utf8', (err, data) => {
    let arr = JSON.parse(data);
    arr.push(arr.length + 1);
    console.log(arr);
    fs.writeFile('./libs/1.json', JSON.stringify(arr), err => {
        console.log('写入成功');
    });
});

案例:filter过滤分类json文件

const fs = require('fs');

// 同步方法
// 读取JSON文件并转数组
let people = JSON.parse(fs.readFileSync('./1.json', 'utf8'));

// 数组方法filter过滤
const man = people.filter(item => item.gender === '男');
const woman = people.filter(item => item.gender === '女');

// 完整写法
// constman = people.filter(item => {
//     if (item.gender === '男') {
//         return true;
//     } else {
//         return false;
//     }
// });

console.log(man, woman);

fs.appendFileSync('./man.json', JSON.stringify(man));

fs.appendFileSync('./woman.json', JSON.stringify(woman));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Henry_ww

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值