zoukankan      html  css  js  c++  java
  • node.js系列笔记之fs模块《二》

    一:感触

      最近工作比较忙,感觉也比较多,因为工作上的不顺利,再加上加班比较多,所以最近心情不是很好,再加上英语能力差到不行,所以最近半个月学习进度也比较慢,

      但还是告诉自己每天都坚持学一点,即使今天心情再不好,不行也代码,也会看一些相关的文章,或者和一些朋友聊聊技术上的事。抱怨少一些,努力多一些。

    二:fs模块部分api解读

      2.1 fs.readFile,appendFile,writeFile

        

      /**  

       * Created with JetBrains WebStorm.  

       * author: solarstorm_java  * Date: 13-8-28  

       * Time: 下午11:19  

      */

       /**  

        1.fs.readFile(path,encoding,callback[err,data]);  

         path:文件路径

        encoding:字符集编码--utf8  

        callback:回调函数,此函数有两个参数err,data--文件数据

        2.fs.appendFile(path,data,encoding,callback[err]);

        path:文件路径

        data:要写入文件的数据

        encoding:字符集编码--utf8

        callback:回调函数,此函数有一个参数err  

        3.fs.writeFile(path,data,encoding,callback[err]);

        path:文件路径

        data:要写入文件的数据

        encoding:字符集编码--utf8  

        callback:回调函数,此函数有一个参数err

      */

    var http = require('http'); var url = require('url');

    var fs = require('fs');

    http.createServer(onRequest).listen(8888);

    function onRequest(request, response){    

      var path = '/upload/test.js';    

      fs.readFile(path,'utf8',function(err,data){

            if (err) throw err;

            //要写入的新数据        

        var newData = 'newData write...';

           //处理空格        

        var matchData  = data.replace(/s+/g,'');

           if (matchData != null && matchData.length > 0 && matchData != '') {            

          //追加新内容            

          fs.appendFile(path,newData,'utf8',function(err){                

            if(err) throw err;                

            console.log('data append success.....');                

            response.end();            

          })        

        }else {            

          //直接将内容写入到文件            

          fs.writeFile(path,newData,'utf8',function(err){                

            if(err) throw err;                

            console.log('data wirte success.....');                

            response.end();            

          })

             }

         });

    }

     2.2 fs.exists fs.rename

      

    /** 

      Created with JetBrains WebStorm.  

      autor: solarsorm_java  * Date: 13-8-30  

      Time: 下午4:25    

    */

    /**    

      1.fs.exists(path, callback)        

        Test whether or not the given path exists by checking with the file system.        

        Then call the callback argument with either true or false.        

        通过检测文件系统测试给定路径的文件是否存在,然后调用回调函数,无论返回的是true还是false        

        path:文件路径        

        callback:回调函数,此回调函数有一个参数,如果文件存在则返回true,否则返回false

        2.fs.rename(oldPath, newPath, callback)        

        Asynchronous rename. No arguments other than a possible exception are given to the completion callback.        

        异步的对文件进行重命名。没有异常出现则回调函数不会传递任何参数        

        oldPath:需要重命名文件的原路径        

        newPath:文件重命名以后的路径及文件名称        

        callback:回调函数,此函数接受一个参数err,如果执行成功此参数的值为null

     */

    var http = require('http');

    var fs = require('fs');

    http.createServer(onRequest).listen(8888);

    function onRequest(request, response){    

      var oldPath = '/upload/test.js';    

      var newPath = '/upload/test2.js';    

      fs.exists(oldPath,function(exists){        

        if (exists){            

          fs.rename(oldPath,newPath,function(err){                

            if(err) throw err;                

            console.log('update name success...');                

            response.end();            

          })        

        }else{            

          console.log('file not exists...')            

          response.end();        

        }    

      })

    }

    2.3  fs.mkdir  fs.readdir  fs.rmdir

    /**

      Created with JetBrains WebStorm.   

      Author: solarstorm_java  

      Date: 13-9-5  * Time: 下午4:58  

      To change this template use File | Settings | File Templates.  

    */

    /**

       1.fs.mkdir(path, [mode], callback);    

        Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.    

        异步的创建目录,没有异常那么回调函数不传递任何参数

       2.fs.readdir(path, callback);    

        Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files)    

        where files is an array of the names of the files in the directory excluding '.' and '..'.    

        异步调用readdir,读取目录中的内容。回调函数接受两个参数(err, files),其中files参数是保存了目录中所有文件名的数组('.'和'..'除外)

       3.fs.rmdir(path, callback);    

        Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.    

        异步的移除path所对应的文件或目录,没有异常那么回调函数不传递任何参数  */

    var http = require('http'); var fs = require('fs');

    http.createServer(onRequest).listen(8888);

    function onRequest(request, response){    

      var path = '/upload';    

      var dir = '/20120905';    

      fs.exists(path+dir,function(exists){        

        if(exists){            

          fs.readdir('/upload', function(err, fileNameArray){                

            if(err) throw err;                

            console.log(fileNameArray);

                       fs.rmdir(path+dir,function(err){                    

              if(err) throw err;

                           fs.mkdir(path+dir,function(err){                        

                if(err) throw err;                        

                console.log('delete before create success...');                        

                response.end();                    

              })                

            })            

          })        

        }else{            

          console.log('file not exists...');            

          fs.mkdir(path+dir,function(err){                

            if(err) throw err;                

            console.log('create success...');                

            response.end();            

          })        

        }    

      });

    }

    2.4 fs.utimes  

    /** 

    Created with JetBrains WebStorm.  

    author: solarstorm_java  * Date: 13-9-4  

    Time: 下午3:00  

    */

    /**

        1.fs.utimes(path, atime, mtime, callback)        

        Change file timestamps of the file referenced by the supplied path.        

        改变由路径提供的参考文件的时间戳(此方法改变的是atime--访问时间和mtime--修改时间)

     */

    var http = require('http');

    var fs = require('fs');

    http.createServer(onRequest).listen(8888);

    function onRequest(request, response) {    

      var path = '/upload/test2.js';

          fs.exists(path,function(exists){        

        if(exists){            

          fs.stat(path,function(err, stats){                

            if(err) throw err;

                      //获取文件的访问时间                

            var atime = stats.atime;

                      //获取文件的修改时间                

            var mtime = stats.mtime;

                       console.log('modify before...');                

            console.log(atime + ' ' + mtime);

            fs.utimes(path, new Date(), mtime, function (err) {                    

              if (err) throw err;                    

              console.log('success...');                    

              response.end();

                      });                

            console.log('modify after...');                

            console.log(atime + ' ' + mtime);

                       response.end();            

          });        

        }else{            

          console.log('file not exists...');            

          response.end();        

        }    

      })

    }

    2.5 fs.chown  fs.stat

    /**  *

    Created with JetBrains WebStorm.  

    author: solarstorm_java  * Date: 13-8-31  

    Time: 下午2:50   

    */

    /**

        1.fs.chown(path, uid, gid, callback);        

        Asynchronous chown. No arguments other than a possible exception are given to the completion callback.        

        异步修改文件所有者。没有出现异常,则回调函数不传递任何参数        

        1.path:文件路径        

        2.uid:用户id        

        3.gid:组id        

        4.callback:回调函数,此函数接受一个参数,如果执行成功则此回调函数的参数为null

        2.fs.stat(path, callback);        

        Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.        

        See the fs.Stats section below for more information.        

        异步获取文件状态信息。这个回调函数有两个参数err,stats; stats是一个fs.stats对象

        3.Class: fs.Stats;        

        Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.        

        返回的对象来自于 fs.stat(); fs.last(); fs.fstat(); 和这些方法对应的同步方法,他们都属于这种类型

        4. Class : fs.Stats property             

        { dev: 2054,               

         mode: 33188,               

           nlink: 1,               

         uid: 0,               

           gid: 0,               

         rdev: 0,               

         blksize: 4096,               

           ino: 776477,               

           size: 32,               

           blocks: 8,               

              atime: Wed Sep 04 2013 11:11:08 GMT+0800 (CST),               

          mtime: Wed Sep 04 2013 11:11:08 GMT+0800 (CST),               

         ctime: Wed Sep 04 2013 11:11:08 GMT+0800 (CST) }

     */

    var http = require('http');

    var fs = require('fs');

    var util = require('util');

    http.createServer(onRequest).listen(8888);

    function onRequest(request, response){    

      var path = '/upload/test2.js';    

      fs.exists(path,function(exists){        

        if(exists){            

          fs.chown(path,0,0,function(err){                

            if(err) throw err;                

            console.log('update success...');

                       fs.stat(path,function(err, stats){                    

              if(err) throw err;

                         console.log('如果是文件返回true-->'+stats.isFile());                    

              console.log('如果是目录返回true-->'+stats.isDirectory());                    

              console.log('如果是队列返回true-->'+stats.isFIFO());

                           response.end();                

            })            

          })

            }else{            

        console.log('file not exists...');            

        response.end();        

       }    

     })

    }

     2.6 fs.watchFile

    /**
    * Created with JetBrains WebStorm.
    * Author: solarstorm_java
    * Date: 13-9-5
    * Time: 上午9:46
    * To change this template use File | Settings | File Templates.
    */

    /**

    1.fs.watchFile(filename, [options], listener);
      Watch for changes on filename. The callback listener will be called each time the file is accessed.
      监听指定文件的变化,回调函数listener将在每次访问的时候被调用

      The second argument is optional. The options if provided should be an object containing two members a boolean,
      persistent, and interval, a polling value in milliseconds. The default is { persistent: true, interval: 0 }.

      第二个参数是可选项,如果指定了options参数,它应该是一个包含如下内容的对象:名为persistent的布尔值,
      和名为interval单位为毫秒的轮询时间间隔,默认值为{ persistent: true, interval: 0 }

      The listener gets two arguments the current stat object and the previous stat object:
      listener监听器将获得两个参数,分别标识当前的状态对象和改变前的状态对象


      fs.watchFile(f, function (curr, prev) {
        console.log('the current mtime is: ' + curr.mtime);
        console.log('the previous mtime was: ' + prev.mtime);
      });

      These stat objects are instances of fs.Stat.

      这些状态对象为fs.Stat的实例。

      If you want to be notified when the file was modified, not just accessed you need to compare curr.mtime and `prev.mtime.

      如果你想在文件被修改而不是被访问时得到通知,你还需要比较curr.mtime和prev.mtime的值。
    */


    var http = require('http');

    var fs = require('fs');

    http.createServer(onRequest).listen(8888);


    function onRequest(request, response){

      var path = '/upload/test2.js';

      fs.exists(path, function(exists){
        if(exists){
          console.log('given path file exists... being listener');

          fs.watchFile(path, function(curr, prov){
            console.log('curr--atime->' + curr.mtime + ' prov--atime->' + prov.mtime);
            console.log('curr--mtime->' + curr.mtime + ' prov--mtime->' + prov.mtime);
            response.end();
          });
        }else{
          console.log('given path file not exists...');
          response.end();
        }

      });
    }

    2.7 fs.link   fs.symlink

    /**
    * Created with JetBrains WebStorm.
    * Author: solarstorm_java
    * Date: 13-9-6
    * Time: 下午2:14
    * To change this template use File | Settings | File Templates.
    */


    /**

    1.fs.link(srcpath, dstpath, [callback]);
      Asynchronous link. No arguments other than a possible exception are given to the completion callback.
      异步调用link,创建符号连接,除非回调函数执行过程出现了异常,否则不会传递任何参数。

    2.fs.symlink(srcpath, dstpath, [type], callback);
      Asynchronous symlink. No arguments other than a possible exception are given to the completion callback.
      type argument can be either 'dir', 'file', or 'junction' (default is 'file'). It is only used on Windows
      (ignored on other platforms). Note that Windows junction points require the destination path to be absolute.
      When using 'junction', the destination argument will automatically be normalized to absolute path.
      异步调用symlink--符号连接--软连接,除非回调函数执行过程出现了异常,否则不会传递任何参数。
      type参数可能是目录,文件,节点,默认是文件。它仅用于Windows(在其他平台上忽略)。注意Windows结点需要目的地的路径是绝对的。
      使用“连接”时,目标参数将自动被归一化到的绝对路径。
    */


    var http = require('http');

    var fs = require('fs');

    http.createServer(onRequest).listen(8888);

    function onRequest(response, response){
      var srcPath = "/upload/test2.js";
      var destPath = "/upload/test3.js";
      var destPath2 = "/upload/test4.js";

      //创建硬连接
      fs.link(srcPath,destPath,function(err){
        if(err) throw err;
        console.log('success...');
        response.end();
      });

      //创建软连接--符号连接
      fs.symlink(srcPath, destPath2,function(err){
        if(err) throw err;
        console.log('success...');
        response.end();
      })
    }

    三 软链接,硬链接http://www.cnblogs.com/itech/archive/2009/04/10/1433052.html

      

    1.Linux链接概念
    Linux链接分两种,一种被称为硬链接(Hard Link),另一种被称为符号链接(Symbolic Link)。默认情况下,ln命令产生硬链接。

    【硬连接】
    硬连接指通过索引节点来进行连接。在Linux的文件系统中,保存在磁盘分区中的文件不管是什么类型都给它分配一个编号,称为索引节点号(Inode Index)。在Linux中,多个文件名指向同一索引节点是存在的。一般这种连接就是硬连接。硬连接的作用是允许一个文件拥有多个有效路径名,这样用户就可以建立硬连接到重要文件,以防止“误删”的功能。其原因如上所述,因为对应该目录的索引节点有一个以上的连接。只删除一个连接并不影响索引节点本身和其它的连接,只有当最后一个连接被删除后,文件的数据块及目录的连接才会被释放。也就是说,文件真正删除的条件是与之相关的所有硬连接文件均被删除。

    【软连接】
    另外一种连接称之为符号连接(Symbolic Link),也叫软连接。软链接文件有类似于Windows的快捷方式。它实际上是一个特殊的文件。在符号连接中,文件实际上是一个文本文件,其中包含的有另一文件的位置信息。

    2.通过实验加深理解
    [oracle@Linux]$ touch f1          #创建一个测试文件f1
    [oracle@Linux]$ ln f1 f2          #创建f1的一个硬连接文件f2
    [oracle@Linux]$ ln -s f1 f3       #创建f1的一个符号连接文件f3
    [oracle@Linux]$ ls -li            # -i参数显示文件的inode节点信息
    total 0
    9797648 -rw-r--r--  2 oracle oinstall 0 Apr 21 08:11 f1
    9797648 -rw-r--r--  2 oracle oinstall 0 Apr 21 08:11 f2
    9797649 lrwxrwxrwx  1 oracle oinstall 2 Apr 21 08:11 f3 -> f1

    从上面的结果中可以看出,硬连接文件f2与原文件f1的inode节点相同,均为9797648,然而符号连接文件的inode节点不同。

    [oracle@Linux]$ echo "I am f1 file" >>f1
    [oracle@Linux]$ cat f1
    I am f1 file
    [oracle@Linux]$ cat f2
    I am f1 file
    [oracle@Linux]$ cat f3
    I am f1 file
    [oracle@Linux]$ rm -f f1
    [oracle@Linux]$ cat f2
    I am f1 file
    [oracle@Linux]$ cat f3
    cat: f3: No such file or directory

    通过上面的测试可以看出:当删除原始文件f1后,硬连接f2不受影响,但是符号连接f1文件无效

    3.总结
    依此您可以做一些相关的测试,可以得到以下全部结论:
    1).删除符号连接f3,对f1,f2无影响;
    2).删除硬连接f2,对f1,f3也无影响;
    3).删除原文件f1,对硬连接f2没有影响,导致符号连接f3失效;
    4).同时删除原文件f1,硬连接f2,整个文件会真正的被删除。

    四 node.js fs api

       https://files.cnblogs.com/solarstorm/node.js_fs_api.pdf

  • 相关阅读:
    #pragma 预处理指令
    C++类继承中的构造函数和析构函数 调用顺序
    static_cast与dynamic_cast转换 最简单的理解
    std::map的insert和下标[]访问
    C++有没有string转化int的函数,怎样转换
    c++中在一个类中定义另一个只有带参数构造函数的类的对象
    c++二进制文件的读写
    C++ 包含头文件 和 宏的使用 和 条件编译
    C++ 前置声明 和 包含头文件 如何选择
    C语言 gets()和scanf()函数的区别
  • 原文地址:https://www.cnblogs.com/solarstorm/p/nodefs.html
Copyright © 2011-2022 走看看