-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (77 loc) · 2.1 KB
/
index.js
File metadata and controls
92 lines (77 loc) · 2.1 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var fs = require('fs');
// what is asynchronosity?
// the first example shows how node is asynchromous.
console.log("Before fs.readFile")
fs.readFile('text.txt', 'utf8', function(err, text) {
console.log('fs.readFile() ', text.length);
});
console.log("After fs.readFile");
// lets try using readFileSync, this function will wait for the read to happen
// and then the process moves on
console.log("Before fs.readFileSync");
var text = fs.readFileSync('text.txt', 'utf-8');
console.log("fs.readFileSync ", text.length);
console.log("After fs.readFileSync");
//so what is a callback
function readFileCallback(fileName, callback) {
console.log("In the function");
fs.readFile(fileName, 'utf-8', (err, data) => {
if (err) {
callback(err)
} else {
callback(null, data);
}
})
} //readFile
//here is the callback section
console.log("Before");
readFileCallback('text.txt', function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Callback function ", data.length)
}
})
console.log("After");
//here is the promises section
new Promise((resolve, reject) => {
fs.readFile('text.txt', 'utf-8', (err, data) => {
if (err)
reject(err)
else {
//if the data was read correctly
resolve(data);
}
})
}).then((result) => {
console.log("First then()")
console.log("Promise result ", result.length)
return result.length;
}).then((result) => {
console.log("Second then()")
console.log("Promise result ", result)
}).catch(function(err) {
console.log("catch");
console.log(err)
})
//readFileAsync
function readFileAsync() {
return new Promise(function(resolve, reject) {
fs.readFile('text.txt', 'utf-8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data);
}
})
})
}
async function read() {
try {
var text = await readFileAsync();
console.log("Async Await", text.length);
} catch (err) {
console.log(err);
}
}
read();