G
G
GalileoGalileu2020-12-07 14:48:00
JavaScript
GalileoGalileu, 2020-12-07 14:48:00

Why doesn't 'path' work (Node.js)?

This code:

const http = require('http');
const path = require('path');

const fs = require('fs');
const colors = require('colors');

var base = '/publicHtml';

http.createServer(function (req, res) {
    let pathname = base + req.url + '.html';
    console.log(pathname.green);

    	if (path.basename(pathname) == null) {
    		res.writeHead(404);
    		res.write('Страница не найдена 404\n');
    		res.end();
    	}else{
    		let file = fs.createReadStream(pathname);
    		res.setHeader('Content-type', 'text/html');
    		res.statusCode = 200;

    		file.on('open',function () {
    			file.pipe(res);
    		});

    		file.on('error', function (err) {
    			console.log(err.red);
    		});
    	}
    	// body...
}).listen(3000);
console.log('Server run on port 3000'.green);

The
folder in place does not work, the 'main.html' file is in it.
When requested in the browser (localhost: 3000/publichtml/main or main.html), it gives undefined to the console.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Abdulov, 2020-12-07
@GalileoGalileu

As for referring to, `publichtml/main`it won't work because you don't keep track of that path. But if it’s necessary, then just do it let pathname = path.join(__dirname + req.url)that way. without your base

const http = require('http');
const path = require('path');

const fs = require('fs');

var base = '/publicHtml';

http.createServer(function (req, res) {
    // let pathname = base + req.url + '.html';
    let pathname = path.join(__dirname + base + req.url); // используйте path.join()

    let fileExt = path.extname(pathname); // получаю тип файла из строки в pathname

    if (!fileExt) // если тип файла не обнаружен
        pathname += '.html'; // добавить его в конце строки (соответсвенно к файлу)

  // все что ниже не изменяется
  if (path.basename(pathname) == null) {
    res.writeHead(404);
    res.write('Страница не найдена 404\n');
    res.end();
  }
    else{
    let file = fs.createReadStream(pathname);
    res.setHeader('Content-type', 'text/html');
    res.statusCode = 200;

    file.on('open',function () {
      file.pipe(res);
    });

    file.on('error', function (err) {
      console.log(err);
    });
  }
    	// body...
}).listen(3000);
console.log('Server run on port 3000');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question