How to access in folder images in node.js? - javascript

So in my project I have folder /Pictures and everything else is all over the project folder. My problem is that I can access all the CSS , JS, HTML, but it doesn't let me get this image folder as a source of the web app.
I tried this(doesn't work):
app.get('/water.jpeg', function (req, res) {
res.sendFile(__dirname + '/' + "Pictures" + '/' + "water.jpeg");
});
I want all my images from the /Pictures folder to be a source for my web app.

if image uploads to '/uploads' folder then try like
app.use('/uploads', express.static(process.cwd() + '/uploads'))

__dirname gives you the directory name of entry point file. I don't know where is your entry point file in your application, but that's where you have to start.
By the way, I advise you to use the "join" function of the "path" module to concatenate the path so as it works on linux or window filesystem.

I found a solution by Quora here, thanks to everyone who helped :) :
link

Related

Regular Expresseion in Express routing

I have a file which name is like workbox-someHash.js and that hash will be generated every time I deploy my app. I need to serve it on a route with the same name and what I tried so far is
"(workbox-([a-z0-9]{8})[.]js)",
express.static(__dirname + "/../build/(workbox-([a-z0-9]{8})[.]js)", {})
);
But I'm not winning here. Is there anything I forgot to add or should I do it some other way. Would appreciate any help
If the problem is that you have a bunch of static files with names that match your regex
workbox-([a-z0-9]{8})[.]js
And, they are located in the folder:
__dirname + "/../build"
And, you want to serve those static files automatically, then you can do this:
app.use("/workbox-([a-z0-9]{8})[.]js", express.static(__dirname + "/../build"));
This will match any path request that starts with a / and then matches your workbox regex. It will then look in the __dirname + "/../build" folder for a file with that same name.
A solution may actually not be this difficult. If the build folder this references contains only files that can be served publicly, then you could also just do this:
app.use(express.static(__dirname + "/../build"));
This will take any incoming request and see if the matching path exists in __dirname + "/../build". If it does, it will serve it. This will be true whether it's one of your workbox filenames or any other matching filename that is also in that folder.

the images not displaying on Heroku

im trying to upload images on my app that's been served on heroku and it's says
ENOENT: no such file or directory
this is my code
router.post('/' ,multer({
storage : multer.diskStorage({
destination : (req , file , callback) => {
callback (null,'img')
} ,
filename : (req , file , callback) => {
callback(null , Date.now() + '-' + file.originalname)
}
})
})
and the architecture of my files
controllers
img this is the folder i want to upload to
public
routes
views
app.js
anyone can help >>>>?
https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted
Why are my file uploads missing/deleted?
The Heroku filesystem is ephemeral - that means that any changes to the filesystem whilst the dyno is running only last until that dyno is shut down or restarted. Each dyno boots with a clean copy of the filesystem from the most recent deploy. This is similar to how many container based systems, such as Docker, operate.
As a solution to this, I'd recommend you use an image serving service like imgur.com or cloudinary.com.

Sending multiple Files or folder using node.js Express

So my problem is i was originally serving my files i believe static using
app.use(express.static(clientPath));
Since then i realised i need to get some pentameters from the connecting url.
now when i use the connection as below i only get the index.html so there is no css with it or any images so i was wondering how i can send all my files in the client folder?
app.get('/username/:userID/hash/:hash', function (req,res) {
var userDetails = {
username : req.params.userID,
hash : req.params.hash
}
res.sendFile(path.join(__dirname + '/../client/index.html'));
});
Continue to use the static module to serve static files.
Make sure that the URLs you use to reference CSS, images, etc are still correct (since the URL of the HTML document has changed so relative paths will resolve differently).

node.js - How to send multiple images to a page on the server

How to send images to a page on my node.js server along with the html? How do I use express static to send images? (Need an example here)
Server side ->
app.get('/', function (req, res) {
res.sendFile(__dirname + '/login.html');
});
app.post('/m', function (req, res) {
res.sendFile(__dirname + '/m/a.png');
res.sendFile(__dirname + '/m/b.png');
res.sendFile(__dirname + '/m/c.png')
res.sendFile(__dirname + '/m/d.html');
});
In a web server, you don't just send multiple images to a page. Instead, the browser requests the page HTML, parses it, finds <img> tags in the HTML and then requests each of those images separately and your web server responds to each separate image request by sending the requested image.
If you put all your images in a common folder, then you can use express.static() to handle all the image requests with one line of code. For example a line of code like this:
app.use("/image", express.static(path.join(__dirname, "public")));
Would serve all image requests for URLs like this:
/image/a.png
/image/b.png
by finding the matching a.png and b.png in the "public" sub-directory below __dirname (which is the directory of the script). You can read more about express.static() here. You can obviously play with the path of the URL you want to use and the path where the images are found. The two just have to work together so that express.static() can find the right image in the corresponding place on the server hard drive where you've put it.
There is often some confusion in understanding how the separate path components in app.use() and express.static() work together. In the above example, the "/image" will be part of the request URL and this app.use("/image", ...) tells express that you want to apply this particular middleware to any request path that starts with /image.
Then path.join(__dirname, "public") is telling express.static() to take the rest of the URL path after the /image and look for that in the subfolder public below the directory __dirname. So, if the browser requests /image/a.png, the app.use() statement will trigger because /image matches that URL and then express.static() will try to find the remaining part of the path a.png in the directory you told it to look in.
On your server hard disk, this would look like this:
/myproject/
app.js
login.html
/public
a.png
b.png
I've shown login.html in the same directory as app.js only because that's how you're code seems to be currently written. I personally don't put any public files in the same directory as my server scripts because I want it to be easy to not make mistakes and accidentally expose my server files to the public.
I would more typically do it like this:
/myproject/
app.js
/public
login.html
a.png
b.png
app.use("/image", express.static(path.join(__dirname, "public")));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, "public", "login.html"));
});
Or, just let express.static() serve the login.html file too.

onload js call not working with node

I am starting to learn node.js, for now I am just trying to execute my old none node app with node. In this app, I have a html page with a body calling an onload js function. It's working just fine.
Now I have a a node app: app.js, simple as that:
var express = require ('express');
var app = express ();
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ketcher'));
app.use(express.static(__dirname +'/ChemAlive_JS'));
app.get('/', function(req, res) {
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/ChemAlive_Interface.html');
});
app.listen(8080);
And in the .html I still have:
<body onload="ketcher.init();">
but the function I want to load is not load at all anymore.
Any clue?
Thanks
You have not provided a lot of info in the question but from what you provide I can have few suggestions:
Suggestions
Instead of adding a lot of express.static uses:
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ketcher'));
app.use(express.static(__dirname +'/ChemAlive_JS'));
put those files (and directories) that you want to be served into one directory, e.g. called static, and use express.static once:
app.use(express.static(__dirname + '/static'));
or better yet, using the path module:
app.use(express.static(path.join(__dirname, 'static')));
you need to require the path module first with:
var path = require('path');
Now, instead of serving the single file for the '/' route with:
app.get('/', function(req, res) {
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/ChemAlive_Interface.html');
});
just put that file into the static directory as index.html so it will be served by the express.static middleware automatically.
Rationale
The way you have it configured currently, is that e.g. everyone can download your Node application - app.js with all of its configuration and even submodules etc.
Also, by using the express.static middleware many times I suspect that you are not sure how the files in those directories will be mapped to URLs.
Having a one place for static files makes it easy to verify whether any script tags have correct paths etc.
My guess
You don't provide enough info to be sure but my guess is that the JavaScript files for the main HTML file are not loaded correctly but you provide not enough info to be sure.
You can open the developer tools console in the browser and reload the page while the console is open and see for errors.
I suspect that the ketcher.init() method is being run but either the method, or the ketcher object is undefined, because some <script> tags failed to be loaded.
Example
The full example after following my suggestions would be much simpler:
var path = require('path');
var express = require ('express');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.listen(8080);
Maybe I would add some output to see what's going on:
var path = require('path');
var express = require ('express');
console.log('starting app.js');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.listen(8080, function () {
console.log('listening on http://localhost:8080/');
});
And now you will have all files that can be served to the browser in one place: in the static directory in this example.
Working app
You can see my example of a working Express application serving static files on GitHub:
https://github.com/rsp/node-express-static-example
In this example the directory for static files is called html but you can call it how you want, as long as it's consistent with how you use the express.static middleware.
You can start from this example project and just put your own files into the directory where express.static is told to look for files to serve.
You can also change the port number to match your needs.
More examples to do the same with and without Express, plus better explanation:
https://github.com/rsp/node-static-http-servers
More hints
The onload callback may not be fired if the page is waiting for some resources to load.
To see if your onload callback is firing you can change it to:
<body onload="alert('onload callback fired');">
Also the ketcher object may be not initialized or it may not have the init() method. After the page is loaded you can open the JavaScript Console and try running the method manually to see if it would work if it was fired:
ketcher.init();
You can also try commands like:
console.dir(ketcher.init);
console.dir(ketcher);
console.log(typeof ketcher.init);
console.log(typeof ketcher);
to see if the ketcher object contains what it should.
Even if the GET localhost:8080/ketcher.js gives a 200 OK status, it can still load some other resources that are not available or, as is very common with code that serve files with res.sendFile() (though unlikely in this case), it can serve HTML instead of JavaScript and result in a cryptic parse error on the < character - see this question for example:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 while acess static files in node server
Other related answers:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
Sending whole folder content to client with express
Loading partials fails on the server JS
Node JS not serving the static image

Categories