0
点赞
收藏
分享

微信扫一扫

【JavaScript进阶学习】nodeJS内置模块 - fs

M4Y 2022-03-21 阅读 112
  1. fs:文件系统,用来操作计算机中的文件。对文件进行,增,删,改,查

  2. 增:创建文件或修改文件(覆盖式修改内容)

    • 创建文件或修改文件
    • fs.writeFile(参数1,参数2,参数3);
    • 参数1:要写的文件路径+文件名
    • 参数2:要写入文件的内容
    • 参数3:写完成之后的回调函数(成功和失败都会执行的函数)
    fs.writeFile('./hello.txt', 'hello world', function (abc) {
    console.log(abc);
    })
    
    • 读取文件
    • fs.readFirle(参数1, 参数2, 参数3);
    • 参数1:要读的文件路径+文件名
    • 参数2:读取到的数据的字符编码(可省略,默认Buffer数据)
    • 参数3:读取完之后的回调函数(成功和失败都会执行的函数)
    //utf-8只适合用来解析文本类数据,如中英文,html,css,js,不适合解析媒体类资源:如音频,,视频...
    fs.readFile('./hello.txt', 'utf-8', function (error, date) {
    if (error) {
       console.log('文件不存在,读取失败');
    } else {
       console.log(date)
    }
    })
    
    • 在原文件内容的基础上增加数据
    //先读取数据
    fs.readFile('./hello.txt', 'utf-8', (error1, date) => {
    if (error1) return;
    //修改数据,再存回去
    fs.writeFile('./hello.txt', date + '哈哈哈', (error2, date) => {
        if (error2) {
            console.log('写入失败');
        } else {
            console.log('写入成功');
        }
    })
    

})
4. 改:改文件名 - `fs.rename(参数1, 参数2, 参数3);` - 参数1:要修改的文件路径+文件名 - 参数2:修改之后的文件路径+文件名 - 参数3:回调函数(成功和失败都会执行的函数)js
fs.rename(’./hello.txt’, ‘./world.txt’, (error) => {
console.log(error);
})
5. 删:删除文件 - `fs.unlink(参数1, 参数2);` - 参数1:要删除的文件路径+文件名 - 参数2:删除完成之后的回调函数(成功和失败都会执行的函数)js
fs.unlink(’./world.txt’, error => {
console.log(error);
})
```

举报

相关推荐

0 条评论