http://shichuan.github.io/javascript-patterns/
fs函式官方文件:
http://nodejs.org/api/fs.html
main.js (高亮為讀檔部分)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | var fs = require( "fs" ); var multiplication_table = function () { var i = 0, j = 0, output = "" ; for (i=1;i<=9;i++) { for (j=1;j<=9;j++) { output += j + "*" + i + "=" + j*i + ((j==9)? "" : "\t" ); } output += ((i==9)? "" : "\r\n" ); } return output; }; var data = multiplication_table(); //Method A fs.writeFile( "tableA.txt" , data, function (err) { if (err) throw err; console.log( "A Write done." ); fs.readFile( "tableA.txt" , "utf8" , function (err, utf8Read) { if (err) throw err; console.log(utf8Read); console.log( "A Read done." ); }); }); //Method B fs.open( "tableB.txt" , "w" , 0644, function (err, fd) { if (err) throw err; fs.write(fd, data, 0, "utf8" , function (err) { if (err) throw err; fs.closeSync(fd); console.log( "B Write done." ); fs.stat( "tableB.txt" , function (err, stats) { fs.open( "tableB.txt" , "r" , function (error, fd) { var buffer = new Buffer(stats.size); fs.read(fd, buffer, 0, buffer.length, null , function (error, bytesRead, buffer) { var utf8Read = buffer.toString( "utf8" , 0, buffer.length); console.log(utf8Read); fs.close(fd); console.log( "B Read done." ); }); }); }); }); }); |
輸出結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | B Write done. A Write done. 1*1=1 2*1=2 3*1=3 4*1=4 5*1=5 6*1=6 7*1=7 8*1=8 9*1=9 1*2=2 2*2=4 3*2=6 4*2=8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18 1*3=3 2*3=6 3*3=9 4*3=12 5*3=15 6*3=18 7*3=21 8*3=24 9*3=27 1*4=4 2*4=8 3*4=12 4*4=16 5*4=20 6*4=24 7*4=28 8*4=32 9*4=36 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 6*5=30 7*5=35 8*5=40 9*5=45 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 7*6=42 8*6=48 9*6=54 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 8*7=56 9*7=63 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 9*8=72 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 B Read done. 1*1=1 2*1=2 3*1=3 4*1=4 5*1=5 6*1=6 7*1=7 8*1=8 9*1=9 1*2=2 2*2=4 3*2=6 4*2=8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18 1*3=3 2*3=6 3*3=9 4*3=12 5*3=15 6*3=18 7*3=21 8*3=24 9*3=27 1*4=4 2*4=8 3*4=12 4*4=16 5*4=20 6*4=24 7*4=28 8*4=32 9*4=36 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 6*5=30 7*5=35 8*5=40 9*5=45 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 7*6=42 8*6=48 9*6=54 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 8*7=56 9*7=63 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 9*8=72 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 A Read done. |
學習步驟:
1. 學習如何使用fs寫檔及讀檔。
2. 學習JSON結構及應用。
作業3:
1. 利用讀檔寫檔設計一個可編輯公告內容的網站。