Skip to content

Commit 627c7ec

Browse files
committed
Fix path separator issue in Chapter 20
Issue marijnh#446
1 parent fb0a429 commit 627c7ec

1 file changed

Lines changed: 8 additions & 6 deletions

File tree

20_node.md

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -794,15 +794,15 @@ it relative to the program's working directory.
794794

795795
```{includeCode: ">code/file_server.js"}
796796
const {parse} = require("url");
797-
const {resolve} = require("path");
797+
const {resolve, sep} = require("path");
798798
799799
const baseDirectory = process.cwd();
800800
801801
function urlPath(url) {
802802
let {pathname} = parse(url);
803803
let path = resolve(decodeURIComponent(pathname).slice(1));
804804
if (path != baseDirectory &&
805-
!path.startsWith(baseDirectory + "/")) {
805+
!path.startsWith(baseDirectory + sep)) {
806806
throw {status: 403, body: "Forbidden"};
807807
}
808808
return path;
@@ -820,16 +820,18 @@ may, for example, include `"../"` to refer to a parent directory. So
820820
one obvious source of problems would be requests for paths like
821821
`/../secret_file`.
822822

823-
{{index "path package", "resolve function", "cwd function", "process object", "403 (HTTP status code)"}}
823+
{{index "path package", "resolve function", "cwd function", "process object", "403 (HTTP status code)", "sep binding", "backslash character", "slash character"}}
824824

825825
To avoid such problems, `urlPath` uses the `resolve` function from the
826826
`path` module, which resolves relative paths. It then verifies that
827827
the result is _below_ the working directory. The `process.cwd`
828828
function (where "cwd" stands for "current working directory") can be
829-
used to find this working directory. When the path doesn't start
829+
used to find this working directory. The `sep` variable from the
830+
`path` package is the system's path separator—a backslash on Windows
831+
and a forward slash on most other systems. When the path doesn't start
830832
with the base directory, the function throws an error response object,
831-
using the HTTP status code indicating that access to the resource
832-
is forbidden.
833+
using the HTTP status code indicating that access to the resource is
834+
forbidden.
833835

834836
{{index "file server example", "Node.js", "GET method"}}
835837

0 commit comments

Comments
 (0)