一:感触

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

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

二: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 + '\n' + 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 + '\n' + 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

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

node.js系列笔记之fs模块《二》的更多相关文章

  1. Node.js学习笔记(四) --- fs模块的使用

    目录 . fs.stat 检测是文件还是目录 . fs.mkdir 创建目录 . fs.writeFile 创建写入文件 . fs.appendFile 追加文件 . fs.readFile 读取文件 ...

  2. node.js系列笔记之node.js初识《一》

    node.js系列笔记之node.js初识<一> 一:环境说明 1.1 Linux系统CentOS 5.8 1.2 nodejs v0.10.15 1.3 nodejs源码下载地址 htt ...

  3. Node.js学习笔记(一) --- HTTP 模块、URL 模块、supervisor 工具

    一.Node.js创建第一个应用 如果我们使用 PHP 来编写后端的代码时,需要 Apache 或者 Nginx 的 HTTP 服务器, 来处理客户端的请求相应.不过对 Node.js 来说,概念完全 ...

  4. Node.js实战12:fs模块高级技巧。

    通过fs模块使用流 fs模块同样有流接口,如下例: var fs = require("fs"); var read_able = fs.createReadStream(&quo ...

  5. Node.js实战11:fs模块初探。

    fs模块封装了对文件操作的各种方法,比如同步和异步读写.批量操作.流.监听. 我们还是通常例程学习, 获取目录下的文件清单: var fs =require("fs"); fs.r ...

  6. Node.js实战13:fs模块奥义!开发一个数据库。

    本文,将使用fs开发一种简单的文件型数据库. 数据库中,记录将采用JSON模式,内容型如: {"key":"a","value":" ...

  7. Node.js学习笔记(2):基本模块

    Node.js学习笔记(2):基本模块 模块 引入模块 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式.在No ...

  8. Node.js学习笔记(二):模块

    模块是 Node.js 应用程序的基本组成部分,文件和模块是一一对应的.一个 Node.js 文件就是一个模块,这个文件可能是 JavaScript 代码.JSON 或者编译过的 C/C++ 扩展. ...

  9. 系列文章--Node.js学习笔记系列

    Node.js学习笔记系列总索引 Nodejs学习笔记(一)--- 简介及安装Node.js开发环境 Nodejs学习笔记(二)--- 事件模块 Nodejs学习笔记(三)--- 模块 Nodejs学 ...

随机推荐

  1. MySQL检查连接的最大数量和改变的最大连接数

    版权声明:本文博主原创文章.博客,未经同意不得转载.

  2. POJ3342——Party at Hali-Bula

    Party at Hali-Bula Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 5418   Accepted: 192 ...

  3. 我的MYSQL学习心得(十二)

    原文:我的MYSQL学习心得(十二) 我的MYSQL学习心得(十二) 我的MYSQL学习心得(一) 我的MYSQL学习心得(二) 我的MYSQL学习心得(三) 我的MYSQL学习心得(四) 我的MYS ...

  4. JS操作cookie的实例

    <script type="text/javascript"> //写cookies函数 function SetCookie(name, value)//两个参数,一 ...

  5. 使用IntelliLock加密授权你的.Net程序

    原文:使用IntelliLock加密授权你的.Net程序 转自:http://www.nsoff.com/post/2012/05/23/%E4%BD%BF%E7%94%A8IntelliLock%E ...

  6. Java清理临时目录文件Demo(一)

    /** * 删除单个文件 * * @param sPath * 被删除文件的文件名 * @return 单个文件删除成功返回true,否则返回false */ public static boolea ...

  7. 通过Web Api 和 Angular.js 构建单页面的web 程序

    通过Web Api 和 Angular.js 构建单页面的web 程序 在传统的web 应用程序中,浏览器端通过向服务器端发送请求,然后服务器端根据这个请求发送HTML到浏览器,这个响应将会影响整个的 ...

  8. Math.random引发的骗术,绝对是用随机数骗前端妹纸的最佳方法

    我觉得今天我运气特好,今天我们来赌一赌,我们来搞个随机数,Math.floor(Math.random() * 10),如果这个数等于0到7,这个月的饭,我全请了,如果是8或9,你就请一个礼拜成不?于 ...

  9. 初探Django线程发送邮件

    最近一直在纠结一个邮件发送的问题. 在本地Linux下搭建程序,不填写EMAIL设置就可以成功发送邮件,在远端的云服务器下的Linux环境就发送不了.在windows下搭建的程序也不能发送注册邮件,很 ...

  10. erlang mnesia数据库简单应用

    mnesia是erlang自带的分布式数据库,基于ets和dets实现的.mnesia兼顾了dets的持久性和ets的高性能,可以自动在多个erlang节点间同步数据库.最关键的是,mnesia实现了 ...