25. // synchrounous example
console.log('hello world');
var fs= require("fs");
var data = fs.readFileSync('content.txt');
console.log(data.toString());
console.log("End");
End 顯⽰在最後⾯,就像我們以往⼀般寫程式⼀樣: c++, C#, PHP, java
26. 非同步執⾏(NON-BLOCKING)
➤ nano index2.js
// aynchrounous example
var fs = require("fs");
fs.readFile('content.txt', function(err, data) {
if (err) return console.error(err);
console.log( data.toString() );
});
console.log("Game over");
27. Game over
I love node.js !
But I love to write app as well.
Output:
發⽣生了了什什麼事???
31. 練習時間 PRACTICE TIME
➤ Q1: 把原本的範例故意打錯⼀個字,看會發⽣什麼事︖
➤ Q2: 製作⼀個callback 的範例
➤ 使⽤ fs.readFile 在完成讀取後使⽤ callback 顯⽰讀取的檔案
內容
➤ 在讀取前顯⽰ “start reading a file”
➤ 在程式最後⼀⾏顯⽰ “end of the file”
32. 解答
const fs = require('fs')
console.log('start reading a file...')
fs.readFile('file.md', 'utf-8', function (err, content) {
if (err) {
console.log('error happened during reading the file')
return console.log(err)
}
console.log(content)
})
console.log('end of the file')