Node.js dirty Is it possible to reload a dirty database? - javascript

How do make the server reload the Dirty database when it's trying to get something from it? Because when I edit the database file with a text editor, and reload the browser, it doesn't update the page.
"reloadDB();" is where I want to reload the db.
Code example
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
var html = db.get(pathname);
//Check if the requsted file is CSS or JS
if (/\.(css)$/.test(pathname) || /\.(js)$/.test(pathname)){
fs.createReadStream(__dirname + pathname, {
'bufferSize': 4 * 1024
}).pipe(response);
} else if (!!html && pathname !== '/admin' ) {
//Pages from our Dirty DB
response.writeHead(200, {'Content-Type': 'text/html'});
//reloadDB();
response.end(html);
} else if (pathname === '/admin') {
//Display Admin page
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('Admin!');
} else {
//Show 404 Page
response.writeHead(404, {'Content-Type': 'text/html'});
//reloadDB();
response.end(db.get('404'));
}

You just need to call the .Dirty(path) method of your existing instance; if you look at the source, you'll see that there's a check allowing Dirty() to be used as either an instance method or a constructor.

Related

Loading two different types of data to a webpage with http.createServer's callback

I'm trying to load an HTML page along with two separate CSS files through http.createServer()'s callback. Here's the important part of the code so far:
var server = http.createServer(function (req, res) {
var htmlData = fs.readFileSync(__dirname + "/public/index.html");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(htmlData);
res.end();
}).listen(port);
When I try to load this, it also tries to load the CSS files linked within the HTML file. I've tried both adding direct links within the header and adding a script within the HTML file to add the links to the header, but neither work. How can I do this without putting the content of the CSS files directly within tags in the HTML file?
You are ignoring the request path and giving it the same file each time.
You need to serve the right file based on the request.
For example: if you want to serve two files index.html and style.css:
var server = http.createServer(function (req, res) {
if (req.url === '/' || req.url === '/index.html') { // respond to both / and /index.html
var htmlData = fs.readFileSync(__dirname + "/public/index.html");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(htmlData);
res.end();
}
else if (req.url === '/style.css') { // respond to /style.css
var cssData = fs.readFileSync(__dirname + "/public/style.css");
res.writeHead(200, { 'Content-Type': 'text/css' });
res.write(cssData);
res.end();
}
}).listen(port);

Obtaining 'undefined ' from response.write(string) is JS

I'm creating a http server with JS and Node JS.
It consists of a form where you can input text that should be the pathname of a file. Once you press on submit button, it should show on webpage the content of that file.
I read the content of the file with function file(pathname) and return it as a String. Then I try to to show the content on webpage with:
response.write('File content: '+ string); but it shows 'File content: undefined'
I think my problem is on the response.write(), because when I use console.log() to show the file content is working correctly.
What I'm doing wrong?
Here is the code when you press on submit:
if(url_parts.pathname == '/submit') { //Processing the form content, if the relative URL is '/ submit'
var pathname=url_parts.query['name']; //Read the contents of the field (form) named 'name'
var string = file(pathname); //file(pathname) returns the content of the file.
console.log("Creating a response header")
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"}); //Creating an answer header - we inform the browser that the body of the answer will be plain text
console.log("Creating the body of the response")
response.write('File content: '+ string); // Write content of the file
response.end(); //The end of the response - send it to the browser
console.log("Sending a response")
}
ALL CODE:
var http = require("http");
var url = require("url");
var fs = require('fs');
function file(pathname){
fs.stat(pathname, function(err, stats) {
console.log("----------------------------------------------------------");
console.log("FILE OPERATION RESULT:");
console.log("----------------------------------------------------------");
if (err){ console.log("'" + pathname + "' is not a directory or a file");
} else if(stats.isDirectory()){
console.log("Is a directory");
} else if(stats.isFile()){
console.log("Is a file");
console.log("Reading content...");
console.log("---------------");
fs.readFile(pathname, function (err, data) {
fileContent=data.toString('utf8');
console.log(fileContent);
return fileContent;
});
}
});
}
http.createServer(function(request, response) {
console.log("--------------------------------------")
console.log("The relative URL of the current request: "+request.url+"\n")
var url_parts = url.parse(request.url,true); //parsing (relative) URL
if(url_parts.pathname == '/submit') { //Processing the form content, if the relative URL is '/ submit'
var pathname=url_parts.query['name']; //Read the contents of the field (form) named 'name'
var string = file(pathname);
console.log("Creating a response header")
response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"}); //Creating an answer header - we inform the browser that the body of the answer will be plain text
console.log("Creating the body of the response")
response.write('File content: '+ string); //WRITE FILECONTENT IF PATHNAME IS A FILE
response.end(); //The end of the response - send it to the browser
console.log("Sending a response")
}
else { //Generating the form
console.log("Creating a response header")
response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"}); //Creating a repsonse header - we inform the browser that the body of the response will be HTML text
//and now we put an HTML form in the body of the answer
console.log("Creating a response body")
response.write('<form method="GET" action="/submit">');
response.write('<label for="name">Write pathname</label>');
response.write('<input name="name">');
response.write('<br>');
response.write('<input type="submit">');
response.write('<input type="reset">');
response.write('</form>');
response.end(); //The end of the response - send it to the browser
console.log("Sending a response")
}
}).listen(8080);
console.log("The server was started on port 8080");
console.log("To end the server, press 'CTRL + C'");

Give value from node.js to its server's html

I need to give var into my html like server -> client
I'm not good at english and this situation is hard to explain so i will show you the code
html (index.html):
<script type="text/javascript">
console.log(tmp) //lol!
</script>
node.js:
fs.readFile('./index.html', (err, html) => {
if (err) {
response.statusCode = 404;
response.end(`error!`);
}
else
{
tmp="lol!"
response.write(html);
response.end();
}
});
server should response and give value to client same time. but it didn't work.
i don't want use external modules like express.js or ajax anything need to download things as it's possible
could you help me?
fs.readFile('./index.html', (err, html) => {
if (err) {
}
else
{
var tmp = new Object();
tmp.string = "hello world!"
var go = JSON.stringify(tmp)
res.write(`<div id="data"><div id="list" data-list='${go}'></div></div>`);
res.write(html);
res.end();
}
});
HTML:
var data = JSON.parse(document.getElementById("list").getAttribute("data-list"));
alert(data.string);
make a div element and set attribute, then write in response.

NodeJS - The Node Beginner Book - show function not getting called

I am following the guide in the Node Beginner Book and have managed to get all the way through to the last section, Handling file uploads. This book focuses on JavaScript calling methods and using request and response with very little HTML included only as strings when necessary.
All my console.log statements are showing me the correct file path. But instead of displaying the image I get the following HTML line:
I think the problem is in this line in requestHandlers.js:
response.write("<img src='/show' />");
It is supposed to be calling the show function at the bottom of requestHandlers.js. Look at the Console output at the bottom of this post and you can see that execution never gets into the show function. Source code and Console output is below:
index.js
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;
server.start(router.route, handle);
server.js
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
router.js
function route(handle, pathname, response, request) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, request);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
requestHandlers.js
var querystring = require("querystring"),
fs = require("fs"),
formidable = require("formidable");
var path = require('path');
var file = path.join(__dirname, 'tmp', "test.png");
function start(response) {
console.log("Request handler 'start' was called.");
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="file" name="upload" multiple="multiple"/>'+
'<input type="submit" value="Upload file"/>'+
'</form>'+
'</body>'+
'</html>';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
console.log("File = "+file);
fs.rename(files.upload.path, file, function (error) {
if(error) {
console.log("error");
fs.unlink(file);
console.log(file);
fs.rename(files.upload.path, file);
console.log(file);
}
});
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}
function show(response) {
console.log("Request handler 'show' was called.");
response.writeHead(200, {"Content-Type": "image/png"});
fs.createReadStream(file).pipe(response);
}
exports.start = start;
exports.upload = upload;
exports.show = show;
Console output
C:\Users\pdl\Projects\TestSeparateJS>node index.js
Server has started.
Request for / received.
About to route a request for /
Request handler 'start' was called.
Request for /upload received.
About to route a request for /upload
Request handler 'upload' was called.
about to parse
parsing done
File = C:\Users\pdl\Projects\TestSeparateJS\tmp\test.png
error
C:\Users\pdl\Projects\TestSeparateJS\tmp\test.png
C:\Users\pdl\Projects\TestSeparateJS\tmp\test.png
You're sending the content as plaintext instead of HTML. So the browser never runs it as HTML. That's why you see the <img> text instead of an <img> tag being generated.
In your upload function change this:
response.writeHead(200, {"Content-Type": "text/plain"});
to this:
response.writeHead(200, {"Content-Type": "text/html"});
When using a newer version of node.js, you also might like to change the code files.upload.path into files.upload.filepath

Form is timeouting on submitting without selected file in input type=file

Having a simple form as in the following js Fiddle http://jsfiddle.net/UdugW/ I am POSTing some form data to my node.js application (based on sails.js). This is one of the controller functions from product model:
image_upload: function(req, res) {
if (req.method.toLowerCase() == 'post') {
console.log("request: " + util.inspect(req.body));
if( req.files && req.files.product_image){
fs.readFile(req.files.product_image.path, function (err, data) {
var imageName = req.files.product_image.name;
if(!imageName){
console.log("There was an error with image upload : " + util.index(req.files.product_image));
res.redirect("/product/new_product");
res.end();
} else {
var newPath = UPLOAD_PATH + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
res.writeHead(200, {'content-type': 'text/plain'});
res.end();
return;
});
}
});
}
}else if (req.body) {
console.log("product_name: " + product_name);
console.log("product_price: " + product_price);
console.log("product_description: " + product_description);
res.writeHead(200, {'content-type': 'text/plain'});
res.end();
}
else{
console.log("request err");
res.writeHead(500, {'content-type': 'text/plain'});
res.end();
}
},
I have a problem when I do not select an image for upload, then my POST request is timing out. Any ideas why this may happen ?
9/10 with node.js app, when something is timing out, chances are you forgot to close the socket (at least in my experience). and in your case it's no different :-)
here is the problem: you have this if-statement
if( req.files && req.files.product_image){
but the poor guy doesn't have a matching else-statement :-(
so if that condition is not true... well, nothing happens. execution basically just ends and the browser is left waiting... for ever.
just adding an else-statment with a res.end() inside of it and you should be good.
So something like this
if( req.files && req.files.product_image){
//all the stuff you already have for when it matches
}else{
console.log("No files were included in the post");
res.end();
}

Categories

Resources