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 + '\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模块《二》的更多相关文章
- Node.js学习笔记(四) --- fs模块的使用
目录 . fs.stat 检测是文件还是目录 . fs.mkdir 创建目录 . fs.writeFile 创建写入文件 . fs.appendFile 追加文件 . fs.readFile 读取文件 ...
- node.js系列笔记之node.js初识《一》
node.js系列笔记之node.js初识<一> 一:环境说明 1.1 Linux系统CentOS 5.8 1.2 nodejs v0.10.15 1.3 nodejs源码下载地址 htt ...
- Node.js学习笔记(一) --- HTTP 模块、URL 模块、supervisor 工具
一.Node.js创建第一个应用 如果我们使用 PHP 来编写后端的代码时,需要 Apache 或者 Nginx 的 HTTP 服务器, 来处理客户端的请求相应.不过对 Node.js 来说,概念完全 ...
- Node.js实战12:fs模块高级技巧。
通过fs模块使用流 fs模块同样有流接口,如下例: var fs = require("fs"); var read_able = fs.createReadStream(&quo ...
- Node.js实战11:fs模块初探。
fs模块封装了对文件操作的各种方法,比如同步和异步读写.批量操作.流.监听. 我们还是通常例程学习, 获取目录下的文件清单: var fs =require("fs"); fs.r ...
- Node.js实战13:fs模块奥义!开发一个数据库。
本文,将使用fs开发一种简单的文件型数据库. 数据库中,记录将采用JSON模式,内容型如: {"key":"a","value":" ...
- Node.js学习笔记(2):基本模块
Node.js学习笔记(2):基本模块 模块 引入模块 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式.在No ...
- Node.js学习笔记(二):模块
模块是 Node.js 应用程序的基本组成部分,文件和模块是一一对应的.一个 Node.js 文件就是一个模块,这个文件可能是 JavaScript 代码.JSON 或者编译过的 C/C++ 扩展. ...
- 系列文章--Node.js学习笔记系列
Node.js学习笔记系列总索引 Nodejs学习笔记(一)--- 简介及安装Node.js开发环境 Nodejs学习笔记(二)--- 事件模块 Nodejs学习笔记(三)--- 模块 Nodejs学 ...
随机推荐
- maven_修改setting ,改为自己私服或者OSC开源中国 [为解决sqlite-jdbc 在中央仓库找不到]
因为项目要使用到sqlite ,虽然有现成的jar,但是考虑的项目的易用统一管理,决定还是用maven 结果纠结了半天 sqlite-jdbc 在maven默认的仓库根本找不着,于是乎修改 setti ...
- post与get,这两人到底神马区别??
甲曰:“1. GET使用URL或Cookie传参.而POST将数据放在BODY中. 2. GET的URL会有长度上的限制,则POST的数据则可以非常大. 3. POST比GET安全,因为数据在地址栏上 ...
- Cocos2d-x 2.3.3版本 FlappyBird
Cocos2d-x 2.3.3版本 FlappyBird 本篇博客基于Cocos2d-x 2.3.3, 介绍怎样开发一款之前非常火的一款游戏FlappyBird.本篇博客内容大纲例如以下: 1 ...
- view components介绍
view components介绍 在ASP.NET MVC 6中,view components (VCs) 功能类似于虚拟视图,但是功能更加强大. VCs兼顾了视图和控制器的优点,你可以把VCs ...
- IOC 容器初始化
WebApi 插件式构建方案:IOC 容器初始化 一般来说,一个现代化的网站加载流程是这样的:程序集加载后,我们会初始化 IOC 容器,以便于接下来解析对象用. 我们插件式的开发,这一步更为重要.这是 ...
- WimMaker 2.0 (2013.10) WIM制作工具
WimMaker 2.0 (2013.10) WIM制作工具 可用于制作PE启动内核的Wim文件 说明: 因本软件使用.NET2.0制作,故主要用于制作WIM映像不用于备份还原系统(虽可用,但不专业, ...
- 转载:善待Redis中的数据
Redis是我们数据的保管者,我们可以随时存随时取,大的小的,重要的不重要的,它都毫无怨言的帮我们保存着,甚至有些时候,我们变得很懒,存东西进去的时候顺便还贴张纸:"过了一个星期就帮我扔了吧 ...
- 图解IntelliJ IDEA v13应用服务器的运行配置
初步了解IntelliJ IDEA v13应用服务器以后,接下来我们将继续设置应用服务器的运行配置. Artifacts是IDE在通过运行配置时部署的一个服务.Artifacts包括名称.类型.输出目 ...
- Android总结的基本机制监控事件
研究上午Android底层机制事件监视器,例如下面的摘要: 内核驱动监控硬件状态和行为,由uevent机制将事件发送到用户空间: 通过用户空间UeventObserver从内核监控uevent,处理. ...
- Android高仿雅虎天气(两)---代码结构分析
版本已经升级到1.0.1 源码地址: GitHub:https://github.com/way1989/WayHoo OsChina:http://git.oschina.net/way/WayHo ...