prerender.io with native Node.js - javascript

Im trying to implement prerender.io for my Angular 1.6.0 app running on a native Node.js server
The documentation for setting up the middleware makes use of the connect middleware and specifically cites Express.js
app.use(require('prerender-node').set('prerenderToken', 'TOKEN'));
I am not using Express and was not using the Connect middleware to run my server.
My server.js is as follows:
var app = http.createServer(function(req, res){
var filePath = './debug/index.html';
var uri = req.url;
// Load index.html only when uri is not referencing a sub-directory of ./www (and is thus a URL)
for(i in dir){
if(uri.includes('/'+dir[i])) {
filePath = './debug'+uri;
break;
}
}
fs.exists(filePath, function(exists) {
if(exists){
fs.readFile(filePath, function(err, html) {
if(err){ res.writeHead(500); res.end(); }
else {
var ext = path.extname(filePath);
var contentType = 'text/html';
switch(ext) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.png':
contentType = 'image/png';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
case '.pdf':
contentType = 'application/pdf';
break;
default: contentType = 'text/html';
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(html, 'utf-8');
}
});
} else {
res.writeHead(404);
res.end();
}
});
}).listen(port, function(){
console.log('server is running on port '+port);
});
1) How can I implement prerender.io with this configuration?
2) I did actually install Connect and trying to implement the middleware as follows:
var conn = connect();
conn.use(require('prerender-node').set('prerenderServiceUrl','http://localhost:3000/').set('prerenderToken', 'lqnF62jXABouJiFA2SuA'));
Which I just appended after the server code above.
I am not getting any errors but I do not see that anything at localhost:3000 after running node server. Although, my app runs fine on localhost:8080
How can I get prerender.io set up on this server?

You might could do something like the following, but I'd suggest breaking each function out into its own function to prevent all of the callbacks. Just wanted to leave the code alone so you could see where it was changed.
var prerender = require('prerender-node').set('prerenderToken', 'TOKEN');
var app = http.createServer(function(req, res){
prerender(req, res, function() {
var filePath = './debug/index.html';
var uri = req.url;
// Load index.html only when uri is not referencing a sub-directory of ./www (and is thus a URL)
for(i in dir){
if(uri.includes('/'+dir[i])) {
filePath = './debug'+uri;
break;
}
}
fs.exists(filePath, function(exists) {
if(exists){
fs.readFile(filePath, function(err, html) {
if(err){ res.writeHead(500); res.end(); }
else {
var ext = path.extname(filePath);
var contentType = 'text/html';
switch(ext) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.png':
contentType = 'image/png';
break;
case '.svg':
contentType = 'image/svg+xml';
break;
case '.pdf':
contentType = 'application/pdf';
break;
default: contentType = 'text/html';
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(html, 'utf-8');
}
});
} else {
res.writeHead(404);
res.end();
}
});
});
}).listen(port, function(){
console.log('server is running on port '+port);
});
As for your second question, you might have it installed correctly. Do you see a request on your prerender server console if you go to:
http://localhost:8080/?_escaped_fragment_=

Related

Download a file from NodeJS Server using hapi

I want to create a file download API using hapi.
Without using res.download(), how to do it using reply()?
You can also download a file from stream
const { Readable } = require('stream');
handler: async (request: any, h: Hapi.ResponseToolkit) => {
let stream = Fs.createReadStream(filePath);
let streamData = new Readable().wrap(stream);
return h.response(streamData)
.header('Content-Type', contentType)
.header('Content-Disposition', 'attachment; filename= ' + fileName);
}
To get content type of file you can refer:
getContentType(fileExt) {
let contentType;
switch (fileExt) {
case 'pdf':
contentType = 'application/pdf';
break;
case 'ppt':
contentType = 'application/vnd.ms-powerpoint';
break;
case 'pptx':
contentType = 'application/vnd.openxmlformats-officedocument.preplyentationml.preplyentation';
break;
case 'xls':
contentType = 'application/vnd.ms-excel';
break;
case 'xlsx':
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'doc':
contentType = 'application/msword';
break;
case 'docx':
contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'csv':
contentType = 'application/octet-stream';
break;
case 'xml':
contentType = 'application/xml';
break;
}
return contentType;
}
you need to make a Buffer and then set the header and the encoding for the reply
let buf = new Buffer(xls, 'binary');
return reply(buf)
.encoding('binary')
.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
.header('content-disposition', `attachment; filename=test-${new Date().toISOString()}.xlsx;`);
This solution is valid for hapi v17 and newer
You may use #hapi/inert module for downloading a file.
First, register the plugin with your server.
await server.register(require("#hapi/inert"));
Then in the handler
downloadFile: function (request, h) {
return h.file("name-of-file-to-download-from-local-system", {
mode: "attachment",
filename: "name-to-be-given-to-downloaded-file",
confine: "/path/to/file/", //This is optional. provide only if the file is saved in a different location
});
},
Detailed documentation is available here

How to display image inside HTML document using node.js [duplicate]

This question already has answers here:
Node JS and Webpack Unexpected token <
(5 answers)
Closed 6 years ago.
I'm displaying some text that i've created inside HTML file using node.js (by method createServer).
Everything was working fine until i added picture inside the document, which doesn't get display on the site.
This is my code
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html'});
//read HTML
fs.readFile(__dirname + '//funkcionalnosti.html', function (err, data) {
console.log(data.toString());
res.end(data);
});
This is my code for image inside HTML file
And this is where picture is located
Picture as located same as HTML file, so i dont any ../ are necessary in order for it ti work. I've also tried adding the ful path and subdirectories but the picture won't show.
I've also tried this that i found on stackoverflow, but it's still not working
var image_origial = "diagram.jpg";
fs.readFile(image_origial, function (err, original_data) {
fs.writeFile('diagram.jpg', original_data, function (err) { });
var base64Image = original_data.toString('base64');
var decodedImage = new Buffer(base64Image, 'base64');
fs.writeFile('diagram.jpg', decodedImage, function (err) { });
});
Also tried this
res.write('<img src="data:diagram.jpg/;base64,imagedata">');
Or this
res.write('<img src="data:diagram.jpg/jpg;base64,imagedata">');
But no luck so far, please help me out, im desperate
Any help will be appreciated!!!
How is this a duplicate to "bundle.js:1 Uncaught SyntaxError: Unexpected token <" ?
You need something like this. You haven't handled route for the image that you are trying to access.
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.wav':
contentType = 'audio/wav';
break;
}
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT'){
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
Original Answer https://stackoverflow.com/a/29046869/2861108

How to upload .txt file to local node.js server and read back the file contents?

Basically, I am creating a small game where I save a list of how many times the user has won to a text file and I then want to upload the contents of that text file to my server and would also like the ability to read the contents from my server. Just wondering what's the best way to do this?
My Server:
var http = require('http');
var fs = require('fs');
var path = require('path');
var PORT = 8080;
var server = http.createServer(function (request, response) {
console.log('connection successful');
var filePath = '.' + request.url;
if(filePath == './'){
filePath = './index.html';
}
var extname = path.extname(filePath);
var contentType = 'text/html';
switch(extname){
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
fs.readFile(filePath, function(error, content) {
if(error){
response.writeHead(500);
response.end();
} else{
response.writeHead(200, {'Content-Type': contentType});
response.end(content, 'utf-8');
}
});
}).listen(8080);
Client code function:
var scoresFile;
function xPlayerWinsF(){
xPlayerWins++;
scoresFile = new File('scoresfile.txt');
scoresFile.wrtiteln("X player wins: "+xPlayerWins);
}
Thanks in advance.

Node.js - Styles doesn't apply to page & Google Chrome says: Uncaught SyntaxError: Unexpected token <

I began studying node.js and stuck at the beginning. I was trying to solve this problem several times but no succeed. I was googling, stackoverflowing and found problems like mine. But not exactly or solutions doesn't work for me. Please, help me!
I have simple index.html file with following content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>SimpleApp</title>
<link rel="stylesheet" type="text/css" href="styles/default.css" />
</head>
<body>
Hello, Node!
<script src="js/application.js"></script>
</body>
</html>
And here is simple server in server.js file:
var http = require('http');
var mime = require('mime');
var fs = require('fs');
var server = http.createServer(function(request, response) {
fs.readFile('./index.html', function(error, data) {
if(error) {
response.writeHead(404, {'Content-Type' : 'text/html'});
response.end('<h1>File <index.html> not found.</h1>');
} else {
var contentType = undefined;
if(request.url === '/') {
contentType = 'text/html';
} else {
contentType = mime.lookup(request.url);
}
response.writeHead(200, {'Content-Type' : contentType});
response.end(data);
}
});
});
server.listen(8000, function() {
console.log('Server started.');
})
After I start server - styles doesn't apply to page & Google Chrome says: Uncaught SyntaxError: Unexpected token <.
I know problem inside fs.readFile callback,inside else, but what?
Here is a solution (need to be refactored):
server.js
var http = require('http');
var mime = require('mime');
var fs = require('fs');
var server = http.createServer(function(request, response) {
var filePath = undefined;
var contentType = undefined;
switch(request.url) {
case '/':
filePath = './index.html';
contentType = 'text/html';
break;
case '/styles/default.css':
filePath = './styles/default.css';
contentType = mime.lookup(request.url);
break;
case '/js/application.js':
filePath = './js/application.js';
contentType = mime.lookup(request.url);
break;
default:
filePath = request.url;
contentType = mime.lookup(request.url);
}
fs.readFile(filePath, function(error, data) {
response.writeHead(200, {'Content-Type' : contentType});
response.end(data);
});
});
server.listen(8000, function() {
console.log('Server started.');
});

How to include javascript on client side of node.js?

I'm a beginner of node.js and javascript.
I want to include external javascript file in html code. Here is the html code, "index.html":
<script src="simple.js"></script>
And, here is the javascript code, "simple.js":
document.write('Hello');
When I open the "index.html" directly on a web browser(e.g. Google Chrome), It works.
("Hello" message should be displayed on the screen.)
However, when I tried to open the "index.html" via node.js http server, It doesn't work.
Here is the node.js file, "app.js":
var app = require('http').createServer(handler)
, fs = require('fs')
app.listen(8000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
("index.html", "simple.js" and "app.js" are on same directory.)
I started the http server. (by "bash$node app.js")
After then, I tried to connect "localhost:8000".
But, "Hello" message doesn't appear.
I think the "index.html" failed to include the "simple.js" on the http server.
How should I do?
Alxandr is right. I will try to clarify more his answer.
It happens that you have to write a "router" for your requests. Below it is a simple way to get it working. If you look forward www.nodebeginner.org you will find a way of build a proper router.
var fs = require("fs");
var http = require("http");
var url = require("url");
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200);
if(pathname == "/") {
html = fs.readFileSync("index.html", "utf8");
response.write(html);
} else if (pathname == "/script.js") {
script = fs.readFileSync("script.js", "utf8");
response.write(script);
}
response.end();
}).listen(8888);
console.log("Listening to server on 8888...");
The problem is that nomatter what your browser requests, you return "index.html". So the browser loads your page and get's html. That html includes your script tag, and the browser goes asking node for the script-file. However, your handler is set up to ignore what the request is for, so it just returns the html once more.
Here is a working code.
There should be more cleaner simpler code, but this is very close to minimal.
This code suppose your index.html and other files are under /client dir.
Good luck.
var fs = require('fs');
var url = require("url");
var path = require('path');
var mime = require('mime');
var log = console.log;
var handler = function (req, res)
{
var dir = "/client";
var uri = url.parse(req.url).pathname;
if (uri == "/")
{
uri = "index.html";
}
var filename = path.join(dir, uri);
log(filename);
log(mime.lookup(filename));
fs.readFile(__dirname + filename,
function (err, data)
{
if (err)
{
res.writeHead(500);
return res.end('Error loading index.html');
}
log(data);
log(filename + " has read");
res.setHeader('content-type', mime.lookup(filename));
res.writeHead(200);
res.end(data);
});
}
Your handler is hardcoded to always return the content of /index.html. You need to pay attention to the resource that is being requested and return the right one. (i.e. if the browser asks for simple.js then you need to give it simple.js instead of index.html).
function contentType(ext) {
var ct;
switch (ext) {
case '.html':
ct = 'text/html';
break;
case '.css':
ct = 'text/css';
break;
case '.js':
ct = 'text/javascript';
break;
default:
ct = 'text/plain';
break;
}
return {'Content-Type': ct};
}
var PATH = 'C:/Users/DELL P26E/node_modules'
var http = require("http");
var fs = require('fs');
var url = require("url");
var path = require("path")
var fileName = "D:/index.html";
var server = http.createServer (function (request, response) {
var dir = "D:/";
var uri = url.parse(request.url).pathname;
if (uri == "/") {
uri = "index.html";
}
var filename = path.join(dir, uri);
fs.readFile(filename,
function (err, data) {
if (err) {
response.writeHead(500);
return response.end('Error loading index.html');
}
var ext = path.extname(filename)
response.setHeader('content-type',contentType(ext));
response.writeHead(200);
response.end(data);
});
}).listen(3000);
console.log('Server running on 8124') ;

Categories

Resources