node.js - home page doesn't load but other pages do - node.js

I'm learning node.js. This code is from a class. It has if else statements. The point is to simplify it and one of the ways I'm doing is using switch case. I'm not sure why the home page doesn't load but "other page" and other other page" does.
As a secondary problem, does figlet work on windows? I use npm install figlet in my node_modules folder. Not sure if I can post multiple problems in one thread. If not, I would like to have my home page solved first.
const http = require("http");
const fs = require("fs");
const url = require("url");
const querystring = require("querystring");
// const figlet = require("figlet");
const server = http.createServer((req, res) => {
const page = url.parse(req.url).pathname;
const params = querystring.parse(url.parse(req.url).query);
console.log(page);
switch (page) {
case "/":
fs.readFile("index.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
break;
case "/otherpage":
fs.readFile("otherpage.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
break;
case "/otherotherpage":
fs.readFile("otherotherpage.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
res.end();
});
break;
case "/api":
if ("student" in params) {
if (params["student"] == "leon") {
res.writeHead(200, { "Content-Type": "application/json" });
const objToJson = {
name: "leon",
status: "Boss Man",
currentOccupation: "Baller",
};
res.end(JSON.stringify(objToJson));
} else if (params["student"] != "leon") {
res.writeHead(200, { "Content-Type": "application/json" });
const objToJson = {
name: "unknown",
status: "unknown",
currentOccupation: "unknown",
};
res.end(JSON.stringify(objToJson));
}
}
break;
case "/ccs/style.css":
fs.readFile("css/style.css", function (err, data) {
res.write(data);
res.end();
});
break;
case "/js/main.js":
fs.readFile("js/main.js", function (err, data) {
res.writeHead(200, { "Content-Type": "text/javascript" });
res.write(data);
res.end();
});
break;
default:
figlet("404!!", function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
res.write(data);
res.end();
});
}
});
server.listen(8000);

Did you tried using empty string "" instead of "/" in your case?

Related

Where is my problem coming from not able to load the array on to the page

const server = http.createServer((req, res) => {
const pathName = req.url;
if(pathName === '/' || pathName === '/overview') {
res.end('This is the overview');
} else if (pathName === '/product') {
res.end('This is the product');
} else if (pathName === '/api') {
fs.readFileSync(`${__dirname}/starter/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
res.writeHead(200, { 'Content-type': 'application/json'})
res.end(data);
});
} else {
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello-world'
});
res.end('<h1>Page not found</h1>');
}
});
server.listen(8000, '127.0.0.1', () => {
console.log('Listening to requests on port 8000');
});
I'm trying to get some data to render onto the page though it's not working. I've included a picture of what my environment looks like.
I think the forward slashes in fs.readFileSync(`${__dirname}/starter/dev-data/data.json, 'utf-8', (err, data) => should be back slashes.

Buffer to String malformed coding (Native ZLIB Compression - Node.js)

Hello I am taking JSON passing it through zlib for compressing, storing it as a buffer in a flat file database, and then reading it and sending it out.
Except my problem is the data is all sorts of crazy characters. I've tried .toString() Ive tried the official StringDecoder from Node. I've tried a lot of things but I can't seem to get it in any format other then the .toJSON readable as a JSON buffer when I actually need the outputted final JSON.
Ideas?
WRITING TO FLAT FILE DB
export const writeCollection = (index, timespan, data) => {
zlib.gzip(JSON.stringify(data), (err, result) => {
if (err) {
console.log({ err });
} else {
const keyName = dbCollections.gzip[index].add({
result
});
collectionKeys.gzip[index] = keyName;
writeLogging(timespan, keyName, index, "gzip");
}
});
zlib.brotliCompress(JSON.stringify(data), (err, result) => {
if (err) {
console.log({ err });
} else {
const keyName = dbCollections.brotli[index].add({
result
});
collectionKeys.brotli[index] = keyName;
writeLogging(timespan, keyName, index, "brotli");
}
});
};
READING FROM FLAT FILE DB
export const readCollection = (index, encoding) => {
const encodedRead = encoding.includes("br")
? dbCollections.brotli[index].all()
: dbCollections.gzip[index].all();
return encodedRead[0].result;
};
TRYING TO CONVERT TO JSON
export const testGetQuakeData = (req, res) => {
const encoding = req.headers["accept-encoding"];
try {
const data = readCollection(0, encoding);
console.log(data)
const json = decoder.write(Buffer.from(data));
console.log(json)
// res.set({
// 'Content-Type': 'application/json',
// 'Content-Encoding': encoding.includes('br') ? 'br' : "gzip",
// })
res.send(json)
} catch (err) {
console.log({ err });
res.status(500).send(err);
}
};
FORGOT TO UNZIP WITH ZLIB!
export const testGetQuakeData = (req, res) => {
const encoding = req.headers["accept-encoding"];
try {
const data = readCollection(0, encoding);
encoding.includes("br")
? zlib.brotliDecompress(data, (err, result) => {
err ? res.status(500).send(err) : res.send(decoder.write(result));
})
: zlib.unzip(data, (err, result) => {
err ? res.status(500).send(err) : res.send(decoder.write(result));
});
} catch (err) {
console.log({ err });
res.status(500).send(err);
}
};
HERES THE FUTURE PROD FUNCTION!
export const testGetCompressedQuakeData = (req, res) => {
const encoding = req.headers["accept-encoding"];
try {
const data = readCollection(0, encoding);
encoding.includes("br")
? res.writeHead(200, {
"Content-Type": "application/json",
"Content-Encoding": "br",
"Content-Length": data.length,
})
: res.writeHead(200, {
"Content-Type": "application/json",
"Content-Encoding": "gzip",
"Content-Length": data.length,
})
res.end(data)
} catch (err) {
console.log({ err });
res.status(500).send(err);
}
};
Content Length 6319 (Brotli) vs 63148 (JSON)
Brotli Compression for the win!

TypeError: callback is not a function in nodejs

I am trying learn nodejs and stumble upon this error
TypeError: callback is not a function
when I am trying to call the server using this command.
curl http://localhost:8090/albums.json
and here is the code for my server.js
var http = require('http'),
fs = require('fs');
function load_album(album_name, callback) {
fs.readdir("albums/", +album_name, (err, files) => {
if (err) {
if (err.code == "ENOENT") {
callback(make_error("no_such_album", "That album doesn't exist"));
} else {
callback(make_error("can't load album", "The server is broken"));
}
} else {
//callback(null, files);
var only_files = [];
var path = 'albums/${album_name}/';
var iterator = (index) => {
if (index == files.length) {
var obj = {
short_name: album_name,
photos: only_files
};
callback(null, obj);
return;
}
fs.stat(path + files[index], (err, stats) => {
if (!err && stats.isFile()) {
only_files.push(files[index]);
}
iterator(index + 1);
});
};
iterator(0);
}
});
}
function handle_incoming_request(req, res) {
console.log("incoming request: " + req.method + " " + req.url);
if (req.url == '/albums.json') {
load_album((err, albums) => {
if (err) {
res.writeHead(500, {
"Content-Type": "application/json "
});
res.end(JSON.stringify({
code: "cant_load_albums",
message: err.message
}));
} else {
var output = {
error: null,
data: {
albums: albums
}
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(output) + "\n");
}
});
} else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
//user is requesting contents of album
load_album(req.url.substr(7, req.url.length - 12), (err, photos) => {
if (err) {
res.writeHead(500, {
"Content-type": "application/json"
});
res.end(JSON.stringify(err));
} else {
var output = {
error: null,
data: {
photos: photos
}
};
res.writeHead(200, {
"Content-Type": application / json
});
res.end(JSON.stringify(output) + "\n");
}
});
} else {
res.writeHead(404, {
"Content-type": "application/json"
});
res.end(JSON.stringify({
code: "no_such_page",
message: "No such page"
}));
}
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);
can you tell me what's wrong with my code that I got an error telling me callback isn't a function?
thanks though
for more formatted code then you can go here https://jsfiddle.net/02dbx6m9/
var http = require('http'),
fs = require('fs');
function load_album(album_name, callback) {
fs.readdir("albums/", +album_name, (err, files) => {
if (err) {
if (err.code == "ENOENT") {
callback(make_error("no_such_album", "That album doesn't exist"));
} else {
callback(make_error("can't load album", "The server is broken"));
}
} else {
//callback(null, files);
var only_files = [];
var path = 'albums/${album_name}/';
var iterator = (index) => {
if (index == files.length) {
var obj = {
short_name: album_name,
photos: only_files
};
callback(null, obj);
return;
}
fs.stat(path + files[index], (err, stats) => {
if (!err && stats.isFile()) {
only_files.push(files[index]);
}
iterator(index + 1);
});
};
iterator(0);
}
});
}
function handle_incoming_request(req, res) {
console.log("incoming request: " + req.method + " " + req.url);
if (req.url == '/albums.json') {
load_album("ALBUM NAME", (err, albums) => {
if (err) {
res.writeHead(500, {
"Content-Type": "application/json "
});
res.end(JSON.stringify({
code: "cant_load_albums",
message: err.message
}));
} else {
var output = {
error: null,
data: {
albums: albums
}
};
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify(output) + "\n");
}
});
} else if (req.url.substr(0, 7) == '/albums' && req.url.substr(req.url.length - 5) == '.json') {
//user is requesting contents of album
load_album("Album Name", req.url.substr(7, req.url.length - 12), (err, photos) => {
if (err) {
res.writeHead(500, {
"Content-type": "application/json"
});
res.end(JSON.stringify(err));
} else {
var output = {
error: null,
data: {
photos: photos
}
};
res.writeHead(200, {
"Content-Type": application / json
});
res.end(JSON.stringify(output) + "\n");
}
});
} else {
res.writeHead(404, {
"Content-type": "application/json"
});
res.end(JSON.stringify({
code: "no_such_page",
message: "No such page"
}));
}
}
var s = http.createServer(handle_incoming_request);
s.listen(8090);
You forgot to pass album name parameter in load_album method. That's why album_name parameter is assigned the actual callback, while callback parameter remains undefined.
Here is the root cause of your issue:
load_album((err, albums) => {
// ...
});
The signature for the function requires two parameters, yet you're only passing the first one:
function load_album(album_name, callback) {}
Therein, once called, callback will be undefined, yet you're trying to treat it as a callable. Here's a more succint example of how to reproduce the error:
function foo(bar, baz) {
baz()
}
foo(() => {})

NodeJS Method not allowed

module.exports.login = function (request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
I am using connect with body-parser. When I first time open this app I see login form - nice, but when I submit a form I see in a console 405 Method not allowed error. I was trying to add some headers but it didn't work. Anyone can help?
I finally solved it. The problem was serve-static and serve-index. It was written some extra headers like allowed methods!
I believe the syntax should be:
module.exports = function(request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
or
function login(request, response, next) {
if (request.body.user && request.body.password) {
response.end('submitted');
} else {
common.render('login', function (error, file) {
if (error) {
next(error);
} else {
response.writeHead(200, 'OK', { 'Content-Type': 'text/html' });
var stream = fs.createReadStream(file);
stream.pipe(response);
}
});
}
};
module.exports = login;

Why isn't node serving my image file?

I have a vanilla node.js http server. Everything except my image file works. I just get the broken image icon on the page.
Here is my server code:
"use strict";
class app {
constructor() {
app.loadServer();
}
static loadServer() {
const HTTP = require('http'),
PORT = 1337,
SERVER = HTTP.createServer(function(req, res) {
let httpHandler = function(err, str, contentType) {
console.log('\n\n' + 'Content type: ' + contentType + '\n\n');
if (err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('An error has occurred: ' + err.message);
} else if (contentType.indexOf('image') >= 0) {
res.writeHead(200, { 'Content-Type': contentType });
res.end(str, 'binary');
} else {
res.writeHead(200, { 'Content-Type': contentType });
res.end(str);
}
};
if (req.headers['x-requested-with'] === 'XMLHttpRequest') {
if (req.method == 'POST') {
app.getFormData(req, res);
} else {
console.log("[405] " + req.method + " to " + req.url);
res.writeHead(405, "Method not supported", { 'Content-Type': 'text/html' });
res.end('<html><head><title>405 - Method not supported</title></head><body><h1>Method not supported.</h1></body></html>');
}
} else if (req.url.indexOf('/javascripts/') >= 0) {
app.render(req.url.slice(1), 'application/ecmascript', httpHandler);
} else if (req.url.indexOf('/css/') >= 0) {
app.render(req.url.slice(1), 'text/css', httpHandler);
} else if (req.url.indexOf('/images/') >= 0) {
app.render(req.url.slice(1), 'image/jpg', httpHandler);
} else {
app.render('public/views/index.html', 'text/html', httpHandler);
}
}).listen(PORT, function() {
console.log('-= Francis Server Listening at http://127.0.0.1:' + PORT + ' =-');
});
}
static render(path, contentType, callback) {
const FS = require('fs');
FS.readFile(__dirname + '/' + path, 'utf-8', function(err, str) {
callback(err, str, contentType);
});
}
static getFormData(req, res) {
const FORMIDABLE = require('formidable'),
DO_NAMES = require('./node/NameClass');
let formData = {};
new FORMIDABLE.IncomingForm().parse(req)
.on('field', function(field, name) {
formData[field] = name;
})
.on('error', function(err) {
next(err);
})
.on('end', function() {
let finalName = new DO_NAMES(formData);
res.writeHead(200, {'content-type': 'text/plain'});
res.write('-= Received form: ');
res.end(finalName.getFirstName() + ' ' + finalName.getLastName());
});
}
}
module.exports = app;
It feels like it's trying to serve the image as text instead of picture. I verified that the image is there and readable.
I found the problem.
it happens here:
FS.readFile(__dirname + '/' + path, 'utf-8', function(err, str) {
callback(err, str, contentType);
});
You read the image file as UTF-8 but it is a binary file. That is why the image data is corrupt. Instead you have to use binary as encoding.
You could change your code like this:
static render(path, contentType, callback, encoding) {
const FS = require('fs');
FS.readFile(__dirname + '/' + path, encoding ? encoding : 'utf-8', function(err, str) {
callback(err, str, contentType);
});
}
and then call render like this:
app.render(req.url.slice(1), 'image/jpeg', httpHandler, 'binary');
There are obviously better ways to do it but this requires a minimum amount of change to your code. Just make sure the readFile() encoding is binary for binary files.
Also the correct mime type for jpg is image/jpeg not image/jpg. Most, if not all, browsers won't care but it is more clean.
It looks like your NODE server is setting the wrong MIME type. You can set the MIME type yourself, as you are doing, but this gets awfully painful. I would recommend using a MIME type node module that is made for this exact purpose.
https://www.npmjs.com/package/mime
This npm package does exactly this with very little effort.

Resources