-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
267 lines (220 loc) · 7.68 KB
/
Copy pathindex.js
File metadata and controls
267 lines (220 loc) · 7.68 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import http from 'http'
import fs from 'fs'
import path from 'path'
// import { createFile } from './modules/filesystem.js'
import { getProducts } from './modules/products.js'
import { getUsers } from './modules/users.js'
const server = http.createServer((req, res) => {
if(req.url == '/') {
return res.end('Welcome to our server')
} else if(req.url == '/products') {
const products = getProducts()
const result = products.map(product => product.title)
res.setHeader('Content-Type', 'application/json')
return res.end(JSON.stringify(result))
} else if(req.url == '/users') {
const users = getUsers()
res.setHeader('Content-Type', 'application/json')
return res.end(JSON.stringify(users))
}
res.end('This is our default route')
})
server.listen(3000, () => {
console.log('Server is running :)')
})
/* --------------------- */
/*
# File System
- Built-in Node.js Module ('fs' module)
- Used to work with files and folders
- Common Operations:
- Read Files
- Create Files
- Append Files
- Delete Files
- Create Folders
- Delete Folders
- Synchronous vs Asynchronous File updates:
- Synchronous: Blocks code execution until operation completes
- Eg.: readFileSync, writeFileSync, etc.
- Asynchronous: Does not block execution, uses callback function (Preferred)
- Eg.: readFile, writeFile, etc.
- Async Read File
- Method: readFile()
- Syntax:
fs.readFile(fileName, charEncoding, (error, data) => {
if(error) {
console.log(error)
return
}
console.log(data)
})
- Async Write File
- Method: writeFile()
- Syntax:
fs.writeFile(fileName, data, (error) => {
if(error) {
console.log(error)
return
}
console.log('File created')
})
- Async Append File
- Method: appendFile()
- Syntax:
fs.appendFile(fileName, additionalData, (error) => {
if(error) {
console.log(error)
return
}
console.log('Content added')
})
- Async Delete File
- Method: unlink()
- Syntax:
fs.unlink(fileName, (error) => {
if(error) {
console.log(error)
return
}
console.log('File deleted')
})
- Create Folder
- Method: mkdir()
- Syntax:
fs.mkdir(folderName, (error) => {
if(error) {
console.log(error)
return
}
console.log('Folder created')
})
- Delete Folder
- Method: rmdir()
- Syntax:
fs.rmdir(folderName, (error) => {
if(error) {
console.log(error)
return
}
console.log('Folder deleted')
})
# Path module
- Built-in Node.js module (path)
- Used to work with file and folder paths
- Why path module?
- File paths are different across Operating Systems
- Windows: C:\Users\ankit\Documents
- Mac/Linux: /home/ankit/Documents
- path module handles these differences automatically
- In CommonJS module system, there are 2 reserved keywords:
- __dirname: Absolute path to current directory
- __filename: Absolute path to current file
- Methods:
- .extname(): Returns file extension
- .join(): Join path segments together
*/
/* --------------------- */
// READ FILE
// fs.readFile('content.txt', 'utf-8', (error, data) => {
// if(error) {
// console.log('Error while reading the file', error)
// return
// }
// console.log(data)
// })
// WRITE FILE
// const data = `It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).`
// fs.writeFile('content-2.txt', data, (error) => {
// if(error) {
// console.log('Error while creating the file', error)
// return
// }
// console.log('File created')
// })
// APPEND FILE
// let content = `There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.`
// fs.appendFile('content.txt', '\n' + content , (error) => {
// if(error) {
// console.log('Error while appending the file', error)
// return
// }
// console.log('Content added')
// })
// DELETE FILE
// fs.unlink('content.txt', (error) => {
// if(error) {
// console.log('Error while deleting the file', error)
// return
// }
// console.log('File deleted')
// })
// CREATE FOLDER
// fs.mkdir('assets', (error) => {
// if(error) {
// console.log('Error while creating the folder', error)
// return
// }
// console.log('Folder created')
// })
// DELETE FOLDER
// fs.rmdir('assets', (error) => {
// if(error) {
// console.log('Error while deleting the folder', error)
// return
// }
// console.log('Folder deleted')
// })
// PATH MODULE
// console.log(path.extname('index.js'))
// console.log(path.extname('index.html'))
// console.log(path.extname('resume.pdf'))
// console.log(path.join('assets', 'css', 'index.css'))
// console.log(path.join('modules', 'users', 'login.js'))
/* ---------------------------- */
// Example 1
// let count = 1
// const server = http.createServer((req, res) => {
// if(req.url == '/create-new-file') {
// createFile(`new-file-${count++}.txt`, 'Some content')
// return res.end('New file created')
// }
// res.end('Hi everyone!')
// })
// server.listen(3000, () => {
// console.log('Server is up :)')
// })
// Example 2
// let count = 1
// const server = http.createServer((req, res) => {
// if(req.url == '/favicon.ico') {
// return
// }
// if(req.url == '/') {
// return res.end('Hi everyone!')
// }
// const filePath = path.join('random-files', `${req.url.slice(1)}.txt`)
// createFile(filePath, 'Some content')
// res.end('A new file created')
// })
// server.listen(3000, () => {
// console.log('Server is up :)')
// })
// Example 3
// import { createServer } from 'http'
// const server = createServer((req, res) => {
// if(req.url == '/students') {
// fs.readFile('students.json', 'utf-8', (error, data) => {
// if(error) {
// return console.log('Error reading file', error)
// }
// res.setHeader('Content-Type', 'application/json')
// res.end(data)
// })
// return
// }
// res.end('Welcome to our server')
// })
// server.listen(3000, () => {
// console.log('Server is running :)')
// })