【node.js學習】--(3)--讀寫檔案

來源:互聯網
上載者:User

標籤:node.js

 

讀寫檔案一般讀寫

建立copyFile.js

var fs = require("fs"); function copyFile(src,dest){         varfile = fs.readFileSync(src);//根據檔案路勁讀取檔案         fs.writeFileSync(dest,file);//將內容寫入檔案        }function main(argv){         copyFile(argv[0],argv[1]);}main(process.argv.slice(2));//接受命令參數

執行拷貝:node copyFile “./in.txt” “./out.txt”

運行效果:

將in.txt拷貝為out.txt

 

管道讀寫

修改copyFile函數的內容為:

fs.createReadStream(src).pipe(fs.createWriteStream(dest));   

管道串連了輸入輸出資料流,可以實現大檔案拷貝。

 

遍曆檔案夾同步遍曆

建立travelDir.js

var fs = require("fs");var path = require("path"); function travel(dir, callback) {   fs.readdirSync(dir).forEach(function (file) {       var pathname = path.join(dir, file);//拼接子路徑        if (fs.statSync(pathname).isDirectory()) {//判斷是否是檔案夾           travel(pathname, callback);       } else {           callback(pathname);       }   });} function printDir(argv){                 travel(argv[0],function (pathname) {                   console.log(pathname);         });}printDir(process.argv.slice(2));


對檔案結構為:

testTravelDir/└── fathers    ├── childs    │  ├── child01.txt    │  └── child02.txt    └──father01.txt 2 directories, 3 files

的目錄,遍曆結果為:

非同步遍曆

略

字元編碼

略

------------------------------------------------------------------------------------------------

------------------------------------------------------------------------------------------------

API相關文檔

官方文檔:http://nodejs.org/api/buffer.html

Buffer(資料區塊)

字串和二進位互操作

Stream(資料流)

.on(...);

.end();

.pause();

.resume();

File System(檔案系統)

檔案屬性讀寫:

fs.stat

fs.chmod

fs.chown

檔案內容讀寫:

fs.readFile

fs.readdir

fs.writeFile

fs.mkdir

底層檔案操作:

fs.open

fs.read

fs.write

fs.close

Path(路徑)

.normalize

.join

.extname

 

參考http://www.nodewhy.com/post/15

【node.js學習】--(3)--讀寫檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.