-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter_twenty.js
71 lines (62 loc) · 1.81 KB
/
chapter_twenty.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
//node.js
// search tool
const fsPromises = require('fs').promises;
const path = require('path');
const regexp = new RegExp(process.argv[2]);
const filesToRead = process.argv.slice(3);
async function searchFileContent(file) {
try {
const fileStats = await fsPromises.stat(file);
if (fileStats.isDirectory()) {
const dirContent = await fsPromises.readdir(file);
dirContent.forEach(dirFile => searchFileContent(path.resolve(file, dirFile)));
} else {
const fileContent = await fsPromises.readFile(file, 'utf8');
regexp.test(fileContent) && console.log(file);
};
}
catch (e) {
console.log(e.message);
}
}
filesToRead.forEach(file => searchFileContent(file));
//directory creation
const http = require('http');
const methods = Object.create(null);
http.createServer((request, response) => {
let handler = methods[request.method] || notAllowed;
handler(request)
.catch(error => {
console.log(error.message);
})
.then(({ body, status = 200, type = "text/plain" }) => {
response.writeHead(status, { "Content-Type": type });
if (body && body.pipe) body.pipe(response);
response.end(body);
});
}).listen(8000, () => console.log('app listening on port 8000'));
async function notAllowed(request) {
return {
status: 405,
body: `Method ${request.method} not allowed.`
}
}
methods.MKCOL = async function (request) {
const requestUrl = new URL(request.url, 'http://localhost:8000');
const name = requestUrl.searchParams.get('name');
let stats;
try {
stats = await fsPromises.stat(name)
} catch (err) {
if (err.code != 'ENOENT') throw err;
await fsPromises.mkdir(name);
return { status: 204 }
}
if (stats.isDirectory()) return {
status: 204
};
else return {
status: 400,
body: 'file not a directory'
};
}