-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
93 lines (89 loc) · 2.57 KB
/
promise.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
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
93
import fs from 'fs';
//Promisified Version of readFile
const readFilePromisified=(filepath,encoding)=>{
return new Promise((resolve,reject)=>{
fs.readFile(filepath,encoding,(err,data)=>{
if(err) reject(err);
resolve(data);
})
});
}
readFilePromisified("a.txt","utf-8")
.then((data)=>{
console.log(`File contents: ${data}`);
})
.catch((err)=>{
console.log(`Error while reading file: ${err}`);
})
//Promisified Version of writeFile
const writeFilePromisified=(filepath,contents,encoding)=>{
return new Promise((resolve,reject)=>{
fs.writeFile(filepath,contents,encoding,(err)=>{
if(err) reject(err);
resolve("Content written in file successfully:)");
})
});
}
writeFilePromisified("b.txt","Hello from b.txt. Testing writeFile","utf-8")
.then((data)=>{
console.log(data);
})
.catch((err)=>{
console.log(`Error while writing file: ${err}`);
})
//Promisified Version of cleanFile
// Reads the contents of a file
// Trims the extra space from the left and right
// Writes it back to the file
const cleanFilePromisified=(filepath,encoding)=>{
return new Promise((resolve,reject)=>{
fs.readFile(filepath,encoding,(err,data)=>{
if(err) {
reject(err);
return;
}
const cleanData=data.trim();
fs.writeFile(filepath,cleanData,encoding,(err)=>{
if(err) return reject(err);
else {
resolve("File contents cleaned successfully");
}
})
})
});
}
cleanFilePromisified("b.txt","utf-8")
.then((data)=>{
console.log(data);
})
.catch((err)=>{
console.log(`Error while writing file: ${err}`);
})
//Promisified Version of setTimeout
const setTimeoutPromisified=(timeout)=>{
return new Promise((resolve,reject)=>{
setTimeout(resolve,timeout);
});
}
setTimeoutPromisified(3000)
.then(()=>{
console.log("Async func executed");
})
.catch((err)=>{
console.log(`Error while setting timeout: ${err}`);
});
//Promisified version of unlink
const unlinkPromisified=(filepath)=>{
return new Promise((resolve,reject)=>{
fs.unlink(filepath,(err)=>{
if(err){
reject(err);
return;
}
resolve("File deleted successfully");
})
})
}
unlinkPromisified("b.txt")
.then(data=>console.log(data))
.catch(err=>console.log(`Error deleting file: ${err}`))