Reputation: 743
In my application I use Node.js, React and Express. I want to load pictures from directory on my disc. Let's say that files I want to load are in //localhost:3000/images/own/
(when I type ex. //localhost:3000/images/own/my_pic.jpg browser returns certain picture)
I used to do it with ajax call:
$.ajax({
url: '/images/own',
dataType: 'text',
success: function (data){
//some actions here
}
});
but now I get 404 error 'GET http://localhost:3000/images/own/ 404 (Not Found)'.
I know that file loading with node is often done with fs, but as my script is written in babel (needed in React) i can't use require('fs'). I found https://github.com/OptimalBits/fs.js which I can use (by including it in my html file), but when using it as in the example:
FSFactory(1024*1024, 'images/own', function(err, fs){
if(err){
console.log(err);
}
fs.readdir('/', function(err, entries){
if(err)
console.log(err);
console.log(entries);
});
});
the fs object is empty and readdir returns empty table.
Should I give the directory path in different way or is there any other way to load files? I'm quite new to node, so any help would be appreciated.
Upvotes: 2
Views: 2873
Reputation: 203304
Judging by your question and your comments, I think that you're mixing up frontend and backend code.
Even though both are written in Javascript, frontend (browser) code has more restrictions imposed on it. One such restriction is the ability to read files or directories. This explains why you can't use fs
.
Also, require()
is not a Javascript (as in "part of the language") command, but something that Node (= backend) provides to load modules. Hence, you can't use that (directly) in browsers either.
There are ways to write Node-like code targeted at browsers, where calls to require()
get translated into something that the browser will understand. One such way is browserify
. However, this still doesn't allow you to run specific backend functionality in a browser (in other words, require('fs')
wouldn't get translated to anything useful).
Now, to get back to your actual question: if you want to read a directory on your server that contains image files, and build an image gallery from it, you need to do the directory-reading on your server.
It could work something like this:
Upvotes: 1
Reputation: 1236
When using express
, you can tell express
that you have a directory that needs to be accessible directly via http(s).
For example, if you have a public
dir with your public files, you can make that "visible" this way:
app.use(express.static('public'));
So, if you have the file public/images/own/my_pic.jpg
, it will be accessible via http://localhost:3000/images/own/my_pic.jpg
The only caveat is that you are not getting a file listing on http://localhost:3000/images/own - you'll need to know exactly which files you need.
Upvotes: 0