Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question