HowProgrammingWorks / NodejsStarterKit

Starter Kit for Node.js 16 or later, minimum dependencies 🚀
http://metarhia.com
MIT License
463 stars 102 forks source link

Path separator in Windows #70

Closed liteCarma closed 4 years ago

liteCarma commented 4 years ago

In Windows, the fs.reader method gets paths like '\index.html' while the static() method waits '/index.html'

./lib/application.js

...
  async cacheDirectory(directoryPath) {
    const files = await fsp.readdir(directoryPath, { withFileTypes: true });
    for (const file of files) {
      const filePath = path.join(directoryPath, file.name);
      if (file.isDirectory()) await this.cacheDirectory(filePath);
      else await this.cacheFile(filePath);
    }
    fs.watch(directoryPath, (event, fileName) => {
      const filePath = path.join(directoryPath, fileName);
      this.cacheFile(filePath);
    });
  }
...

./lib/server.js

...
class Client {
  constructor(req, res, application) {
    this.req = req;
    this.res = res;
    this.application = application;
  }

  static() {
    const { url } = this.req;
    const filePath = url === '/' ? '/index.html' : url;
    const fileExt = path.extname(filePath).substring(1);
    const mimeType = MIME_TYPES[fileExt] || MIME_TYPES.html;
    this.res.writeHead(200, { 'Content-Type': mimeType });
    const data = this.application.cache.get(filePath);
    if (data) this.res.end(data);
    else this.error(404);
  }

...
tshemsedinov commented 4 years ago

I haven't ever promised that Starter Kit will support windows, if somebody still use it they may implement such support and propose corresponding pull-request.