Nodejs查找,读写文件

(1),路径处理

1.首先,我们需要注意的文件路径的规范化,nodejs给我们提供了Path模块,normolize方法能帮我们规范化路径:

var path = require('path');

path.normalize('/foo/bar/nor/faz/..'); -> /foo/bar/nor

2.当然还有join合并路径:

var path = require('path');

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); ->/foo/bar/baz/asdf

3.解析路径

var path = require('path');

path.resolve('/foo/bar', './baz'); ->/foo/bar/baz

path.resolve('/foo/bar', '/tmp/file/'); ->/tmp/file

4.在两个相对路径间查找相对路径

var path = require('path');

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); ->../../impl/bbb

5.抽离路径

var path = require('path');

path.dirname('/foo/bar/baz/asdf/quux.txt'); ->/foo/bar/baz/asdf

=================

var path = require('path');

path.basename('/foo/bar/baz/asdf/quux.html') ->quux.html

甚至你还还可以将后缀名去掉,只需要在basename中传入第二个参数,参数为后缀名,例如:

var path = require('path');

path.basename('/foo/bar/baz/asdf/quux.html', '.html'); ->quux

当然文件路径中可能会存在各种不同的文件,我们不可能硬编码后缀来得到我们想要的结果,

所以有一个方法能帮我们得到后缀名:

path.extname('/a/b/index.html'); // => '.html'

path.extname('/a/b.c/index'); // => ''

path.extname('/a/b.c/.'); // => ''

path.extname('/a/b.c/d.'); // => '.'

(2),文件处理

var fs = require('fs');

1.判断文件是否存在

fs.exists(path, function(exists) {});

上面的接口为异步操作的,因此有回调函数,在回调中可以处理我们的各种操作,如果需要同步操作可以用下面的方法:

fs.existsSync(path);

2.读取文件状态信息

1 fs.stat(path, function(err, stats) {
2     if (err) { throw err;}
3     console.log(stats);
4 });

控制台输出states的内容大致如下:

 1 { dev: 234881026,
 2 ino: 95028917,
 3 mode: 33188,
 4 nlink: 1,
 5 uid: 0,
 6 gid: 0,
 7 rdev: 0,
 8 size: 5086,
 9 blksize: 4096,
10 blocks: 0,
11 atime: Fri, 18 Nov 2011 22:44:47 GMT,
12 mtime: Thu, 08 Sep 2011 23:50:04 GMT,
13 ctime: Thu, 08 Sep 2011 23:50:04 GMT }

同时,stats还具有一些方法,比如:

1 stats.isFile();
2 stats.isDirectory();
3 stats.isBlockDevice();
4 stats.isCharacterDevice();
5 stats.isSymbolicLink();
6 stats.isFifo();
7 stats.isSocket();

3.读写文件

fs.open('/path/to/file', 'r', function(err, fd) {

// todo

});

第二个参数为操作类型:

r : 只读

r+ : 读写

w : 重写文件

w+ : 重写文件,如果文件不存在则创建

a : 读写文件,在文件末尾追加

a+ : 读写文件,如果文件不存在则创建

下面为一个读取文件的小例子:

 1 var fs = require('fs');
 2 fs.open('./nodeRead.html', 'r', function opened(err, fd) {
 3 if (err) { throw err }
 4     var readBuffer = new Buffer(1024),
 5     bufferOffset = 0,
 6     bufferLength = readBuffer.length,
 7     filePosition = 100;
 8     fs.read(fd,
 9         readBuffer,
10         bufferOffset,
11         bufferLength,
12         filePosition,
13         function read(err, readBytes) {
14         if (err) { throw err; }
15         console.log('just read ' + readBytes + ' bytes');
16         if (readBytes > 0) {
17             console.log(readBuffer.slice(0, readBytes));
18         }
19     });
20 });

下面为一个写文件的小例子:

 1 var fs = require('fs');
 2 fs.open('./my_file.txt', 'a', function opened(err, fd) {
 3     if (err) { throw err; }
 4     var writeBuffer = new Buffer('hello, world!'),
 5     bufferPosition = 0,
 6     bufferLength = writeBuffer.length, filePosition = null;
 7     fs.write( fd,
 8         writeBuffer,
 9         bufferPosition,
10         bufferLength,
11         filePosition,
12         function(err, written) {
13             if (err) { throw err; }
14             console.log('wrote ' + written + ' bytes');
15     });
16 });

对于文件的读写操作,我们不应该忘记在这些操作都完成之后执行关闭操作,即close();

下面是一个封装的方法,其中就包括了文件的后期关闭操作,使用起来方便:

 1 var fs = require('fs');
 2 function openAndWriteToSystemLog(writeBuffer, callback) {
 3     fs.open('./my_file', 'a', function(err, fd) {
 4         if (err) { return callback(err); }
 5         function notifyError(err) {
 6             fs.close(fd, function() {
 7                 callback(err);
 8             });
 9         }
10         var bufferOffset = 0,
11         bufferLength = writeBuffer.length,
12         filePosition = null;
13         fs.write( fd, writeBuffer, bufferOffset, bufferLength, filePosition,function(err, written) {
14             if (err) { return notifyError(err); }
15             fs.close(fd, function() {
16                 callback(err);
17             });
18         });
19     });
20 }
21 openAndWriteToSystemLog(new Buffer('writing this string'),function(err) {
22     if (err) {
23         console.log("error while opening and writing:", err.message);
24         return;
25     }
26     console.log('All done with no errors');
27 });