Nodejs尋找,讀寫檔案

來源:互聯網
上載者:User

標籤:style   blog   color   使用   os   io   檔案   ar   

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 });

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.