@@ -794,12 +794,13 @@ it relative to the program's working directory.
794794const {parse} = require("url");
795795const {resolve} = require("path");
796796
797- const baseDirectory = process.cwd() + "/" ;
797+ const baseDirectory = process.cwd();
798798
799799function urlPath(url) {
800800 let {pathname} = parse(url);
801801 let path = resolve(decodeURIComponent(pathname).slice(1));
802- if (!path.startsWith(baseDirectory)) {
802+ if (path != baseDirectory &&
803+ !path.startsWith(baseDirectory + "/")) {
803804 throw {status: 403, body: "Forbidden"};
804805 }
805806 return path;
@@ -862,7 +863,7 @@ and whether it is a ((directory)).
862863``` {includeCode: ">code/file_server.js"}
863864const {createReadStream} = require("fs");
864865const {stat, readdir} = require("mz/fs");
865- const {getType} = require("mime");
866+ const mime = require("mime");
866867
867868methods.GET = async function(request) {
868869 let path = urlPath(request.url);
@@ -874,10 +875,10 @@ methods.GET = async function(request) {
874875 else return {status: 404, body: "File not found"};
875876 }
876877 if (stats.isDirectory()) {
877- return {body: await readdir(path).join("\n")};
878+ return {body: ( await readdir(path) ).join("\n")};
878879 } else {
879880 return {body: createReadStream(path),
880- type: getType(path)};
881+ type: mime. getType(path)};
881882 }
882883};
883884```
@@ -1123,6 +1124,24 @@ widely used HTTP method, but it does exist for this same purpose in
11231124the _ ((WebDAV))_ standard, which specifies a set of conventions on top
11241125of ((HTTP)) that make it suitable for creating documents.
11251126
1127+ ``` {hidden: true, includeCode: ">code/file_server.js"}
1128+ const {mkdir} = require("mz/fs");
1129+
1130+ methods.MKCOL = async function(request) {
1131+ let path = urlPath(request.url);
1132+ let stats;
1133+ try {
1134+ stats = await stat(path);
1135+ } catch (error) {
1136+ if (error.code != "ENOENT") throw error;
1137+ await mkdir(path);
1138+ return {status: 204};
1139+ }
1140+ if (stats.isDirectory()) return {status: 204};
1141+ else return {status: 400, body: "Not a directory"};
1142+ };
1143+ ```
1144+
11261145{{hint
11271146
11281147{{index "directory creation (exercise)", "file server example", "MKCOL method", "mkdir function", idempotency, "400 (HTTP status code)"}}
0 commit comments