zoukankan      html  css  js  c++  java
  • nodejs——文件系统

    文件系统里方法有很多但是主要常用的无外乎 创建,打开,读取,添加,删除等方法。

    1.引入fs模块。

    var fs = require('fs');

    2.打开。

    fs.open(path, flags, [mode], callback)

    path:要打开的文件路径。

    flags:打开文件的方式,读/写。

    mode:可选项。 设置文件的模式  读/写/执行  4/2/1

    callback: 回调

      回调接受两个参数:1. err:文件打开失败的错误保存在err里面,如果成功err为null。2. fd:被打开文件的标识。

    fs.open('1.txt', 'r', function(err, fd){
       console.log(err);
       console.log(fd);
       
       if(err){
          console.log("文件打开失败");    
        } else{
          console.log("文件打开成功"); 
        }
       
    })

    当你第一次打开文件成功时,fd实例中返回数字3,就像你平时使用定时器时最后都会返回一个标识符给我们,然后我们根据标识符来操作具体哪一个定时器。当你在下面再打开一次同一个文件,标识符就变成4,累加的状态。

    nodejs问我们提供文件系统模块的方法时,有很多都是有不同版本的,即同步异步。

    异步操作:

    fs.open('1.txt', 'r', function(err, fd){
       console.log(err);
       console.log(fd);
       
       if(err){
          console.log("文件打开失败");    
        } else{
          console.log("文件打开成功"); 
        }
       
    })
    
    console.log("OK");

    此时先输出的是OK。

    同步操作:

    var fd = fs.openSync(path, flags, [mode]);
    
    console.log(fd);

    fd是它的返回值,如果我们想后续操作的话直接在后面写就好了,同步会阻塞后续代码的执行。

    3.读取。

    fs.open('1.txt', 'r', function(err, fd){
       console.log(err);
       console.log(fd);
       
       if(err){
          console.log("文件打开失败");    
        } else{
    
          fs.read(fd, buffer, offset, length, position, callback)
         
        }
       
    })

    fd: 通过open方法成功打开一个文件返回的编号。

    buffer:buffer对象

    offset:新的内容添加到buffer中的起始位置

    length:添加到buffer中内容的长度

    position:读取文件中的起始位置

    callback:回调

      err:

      len:buffer的长度

      newBf:新的buffer对象

    假如1.txt文件的内容是  abcd

    var bf1 = new Buffer('123456789');

    console.log(bf1); // <Buffer 31 32 33 34 35 36 37 38 39>

    fs.read(fd, bf1, 0, 4, null, function(err, len, newBf){

      console.log(bf1) // <Buffer 61 62 63 64 35 36 37 38 39>

      console.log(len) // 4

      console.log(newBf) //<Buffer 61 62 63 64 35 36 37 38 39>

    })

  • 相关阅读:
    Maximum Depth of Binary Tree
    Single Number
    Merge Two Sorted Lists
    Remove Nth Node From End of List
    Remove Element
    Remove Duplicates from Sorted List
    Add Two Numbers
    编译视频直播点播平台EasyDSS数据排序使用Go 语言 slice 类型排序的实现介绍
    RTMP协议视频直播点播平台EasyDSS在Linux系统中以服务启动报错can’t evaluate field RootPath in type*struct排查
    【解决方案】5G时代RTMP推流服务器/互联网直播点播平台EasyDSS实现360°全景摄像机VR直播
  • 原文地址:https://www.cnblogs.com/wusheng2016/p/6803692.html
Copyright © 2011-2022 走看看