Loading Dygraph input inside a node app - javascript

I'm very new to node and am struggling to load the data for Dygraphs on a static page. I believe that my issue is to do with routing. My js for Dygraphs is:
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"../newDataFile.csv",
etc....
I can see in the browser that newDataFile.csv is not being loaded, despite the file being in the root directory.
My routing code looks like this:
router.get('/Dygraphpage', function(req, res) {
res.render('Dygraphpage');
});
I guess that I need to pass the csv file into this routing code, but I don't know how to. Any ideas?!

Figured it out. I am using ExpressJS and the solution was to put the newDataFile.csv inside the Public folder. It then existed at /newDataFile.csv.

Related

Why won't my Hapi backend serve static files with dynamic file names?

I am currently adding new features to a rather big project which has been running for a couple of years. The project uses a Couch DB database, Hapijs in the backend and React in the frontend.
My goal is to add a download button that let's the user (admin) download all the .pdf files from the database sorted by year and bundled in a .zip archive. The server already has a route for similar tasks, which is why I'm expanding the functionality of this route instead of creating a new one from scratch.
The /generate/{query} route handles all the file exports depending on the params in the query string. The query params will always contain the year. The route starts like this:
server.route({
method: 'GET',
path: '/generate/{query*}',
handler: async function(request, h) {
...
}
})
This route starts a long series of asynchronous processes and in the end successfully stores all the .pdf files in a tmp folder, sorted by year and bundled in .zip files. The only thing left to do would be to send the .zip file as a response back to the frontend, where the download is triggered.
This is where I'm having problems:
I am using the inert package to add files to my response with the file() method. If I pass in the path as a hardcoded string (e.g. file('/tmp/2019.zip')), the data is sent to the frontend correctly and the download starts as it should. However, if I try to build the same string dynamically, I get a corrupted .zip file that's only 1MB - 3MB (the original file is 250MB) (once it was 80MB, once 150MB, but both files were corrupted and couldn't be unpacked). I have tried a couple of different approaches to get a dynamic file path (template literals etc.), but they all produced the same result. This is what I'm currently stuck with:
const response = h.file(Path.join(__dirname + '/tmp/' + request.query.year + '.zip'), {
mode: 'attachment',
})
return response
I then created the following test route:
server.route({
method: 'GET',
path: '/test/{query*}',
handler: function(req, res) {
return res.file(Path.join(__dirname + '/tmp/' + req.query.year + '.zip'), {
mode: 'attachment'
})
}
})
...and it works like a charm, no matter which year I pass in as a query param.
This makes it difficult to pinpoint the exact part of my code that causes trouble: there are no issues with dynamically generated file paths in my test route, so that can't be it. The code in the actual route is also executed correctly, but only if the path to the file is hardcoded, so it's obviously not completely broken. For testing purposes I am currently not removing files from the tmp folder, so it can't be a problem with my async functions (the differently sized corrupted .zip files made me wonder if this might have something to do with my problem). But... what else could it be? Why can't I pass dynamic file names in my main route?
Has anybody here ever encountered anything like this? Let me know if you need more details. Any help is appreciated, even the slightest hunch could be of help!

OpenCV.js Assertion failed in detectMultiScale

So I'm relatively new to JavaScript and I'm attempting to learn OpenCV.js for a web app I'm working on. I've been following tutorials like this to try and understand how it works.
However, I've been getting the error below where the haar cascade file isn't being loaded and I can't seem to fix it.
Error: Assertion failed (!empty()) in detectMultiScale, file /build/master-contrib_docs-lin64/opencv/modules/objdetect/src/cascadedetect.cpp
I've looked for resolutions to this problem and most people suggest that you should use the full directory when loading a cascade file. I've tried referencing the file directly and using the full file path, either way doesn't seem to work for me.
This is how I've attempted load the file.
let classifier = new cv.CascadeClassifier();
// Load the haarcascade file
let utils = new Utils('errorMessage');
let faceCascadeFile = 'http://localhost/eeu8cb/xml/haarcascade_frontalface_default.xml';
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
classifier.load(faceCascadeFile)
});
// Checks if the haarcascade file has failed to load
if(!classifier.load(faceCascadeFile)){
console.log('failed to load file.')
}
I've done some error checking which confirms the file isn't being loaded. Any help would be appriciated, cheers.
Some month ago i worked right on OpenCV.js using those tutorials and i remember there was a problem on loading files while not using HTTPS protocol, i solved my problem using IIS Express.
So try using a web server.

How can I display HTML file using nodeJS?

I am trying to display sample.html in an iframe inside index.html, I want to display index.html using NodeJs.
When I displayed the index.html I can see an empty frame. But when I open that index locally on a browser by double-clicking it works perfectly. What should I do to solve this?
Anyone, please help.
For that, I have to use express.
Before using any file, We need to use express.static to tell the node to use the files.
var express = require('express');<br>
var app = express();<br>
app.use(express.static(__dirname + "/directory_where_html_stored"));

How to serve files from express 4.0 public folder as formatted html and not files, based on extension? E.g. format JSON, show images

Hey so anytime I place something in the "public" dir of my express directory, it automatically has a link on my webpage that I like. For example, going to https://website.com/image.jpg will allow me to download an image, and https://website.com/object.json will allow me to download a JSON file, without me having to do anything aside from place these files in my public folder. This is super convenient since I have another script that could be making a bunch of different things that I won't want to specify by name on my server every time I change something.
What I would like to do is modify this serve command so that when I want to retrieve an image, instead of automatically downloading it, it displays it in the browser. This should be as simple as adding an <html> </html> around anything in the public folder that has the .png file ending. Likewise, I would like to stringify any JSON file so that it comes out in a readable format (JSON.stringify(object,null,2));
Basically, I would like to be able to just put something in my public folder and automatically be able to access it in a desirable way based on its file extension. In these two cases the "desirable" way is not downloading the file, but displaying it in-browser in a human-friendly format.
display of static files in nodejs is not a trivial behavior. you'd usually set a folder as static which becomes public and end url fragment is same as file name. Using Express with Nodejs, it looks like this.
app.use(express.static(path.join('.', 'public')));
Because you don't like default implementation, you can rather parse the url manually, check if a file by that name exists, wrap it around appropriate html, and throw it as response.
var fs = require('fs');
app.use(function(req, res, next){
fileName = req.url.substring('https://website.com/'.length);
if(fs.existsSync('public/'+fileName){
if(fileName.substring(fileName.lastIndexOf('.')+1)=='jpg')
res.send('<html><body><img src="public/'+fileName+'"></img></body></html>')
})
As you can see, all urls are checked for files. You can also use a router while placing all public files under some subdirectory like '/public'

Load a directory in a js with flask

I would like to declare in a script, a directory.
$images_dir = '{{url_for('.../pictures')}}';
My flask application directory looks like:
Root
-wep.py
-templates
-gallery.html
-static
-pictures
The picture are located inside the pictures folder, and the html page that contains the script is gallery.html which located in the templates folder.
The purpose of that script is to list all the images that are located in the pictures folder and present them as a gallery view when the gallery.html page is loaded.
The script works fine if I run it in a normal apache webserver though.
When I run the web.py, the debuger gives me the error:
BuildError: ('../pictures', {}, None)
So I think the problem is to declare the directory in flask.
UPDATE:
Im using this guy's script : http://davidwalsh.name/generate-photo-gallery
As you can see in the source code:
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
Im trying to adjust those line to work with flask.
I think you're misunderstanding the purpose of url_for. url_for is for generating a link to one of your application's HTTP endpoints/view functions. You don't need any flask-specific method to get a list of files. You might find glob or os.listdir() helpful for this purpose. Then you can pass a list of the relevant paths to your template for rendering.

Categories