Static Relative Files Not Found with Express `sendFile()` and Custom Root - node.js

I'm trying to serve a static folder, when using dynamic routes, by using res.sendFile() in ExpressJS:
res.sendFile('index.html', { root : path.join(__dirname, 'myStaticContentFolder') });
The file .../myStaticContentFolder/index.html, indeed gets served - hence: the root field correctly adjusts the path to it.
However, all the files within that folder, with paths relative to index.html are not found.
They are searched relative to the URL root instead of the root field path.
Note that the folder is properly served if I use:
app.use('/foo/', express.static(__dirname + '/myStaticContentFolder'));

Related

How to serve static files from root path '/'

I understand that Express needs to be told where to serve static files from using something like server.use(express.static('public'); if all your static files reside in the public folder.
However there are static files in my app which MUST be served from the root of the site e.g.
http://example.com/ads.txt
http://example.com/sitemap.xml
http://example.com/app.webmanifest
I cannot create a separate route for each static file in the root folder because there can be many. When they are bundled up into the dist folder for deployment, they reside in the root of the site alongside the package.json file etc.
How can it be possible to serve the app's homepage at the route of '/' and also static files from that same route? e.g.:
server.use('/', express.static('/client'));
server.get('/', async (req, res) => {
// serve homepage here
})
var app = express()
app.use(express.static('folder_name'))
Or
app.use(express.static(__dirname + '/folder_mame'));
app.set('folder_name', __dirname);
According to official docs:
Serving static files in Express
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express static.
For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are in the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Serving static files Express

Why does require() not require an absolute path but an express.static() does?

I am trying to run my index.js script from outside the project directory. My project structure is as follows:
app
- config
- config.js
- public
- index.html
- src
- index.js
Now when I run my src/index.js from outside my app folder, require() is able to resolve the relative paths
const config = require(`../config/config`);
On the other hand express.static is not able to resolve such relative paths.
e.g. app.use(express.static("../public"));
Why do I need to use path.join and get the absolute path?
require() works off __dirname which is independent of what the current directory was when your app was loaded. It's always the directory where the module is located in, so it is consistent.
express.static() when used with relative paths uses the directory that the main app was launched form, so if you use relative paths, its behavior varies depending upon how you launch the app.
From the express doc for serving static files:
However, the path that you provide to the express.static function is
relative to the directory from where you launch your node process. If
you run the express app from another directory, it’s safer to use the
absolute path of the directory that you want to serve
So, if you want the directory to be module relative, you have to manually combine your path with __dirname to make a full path, as you have discovered.

How to access static files in node.js

I am working on node js, where I have the following directories: C:\wamp64\www\Scrapper. In the Scrapper folder, I have:
/Controllers/main.js
/Public/index.html
/server.js
What I did is, I have included the main.js in the index.html as:
<script src="/Controllers/main.js"></script>
Also, I have declared these two folders as static in node js server.js file which is located in the main directory i.e. /Scrapper. When I run the app, it says:
http://localhost:8080/Controllers/main.js net::ERR_ABORTED 404 (Not Found)
The way I declared the static files in server.js is :
app.use(express.static(__dirname + "/Public"));
app.use(express.static(__dirname + "/Controllers"));
app.use(body_parser.json());
I don't know what the problem is. All I want is to include the main.js file in the index.html. It's a client site script which should run within that folder.
For example you have declared a static folder like
app.use(express.static(`${__dirname}/assets`))
and inside assets, you have images folder
then you can access the files i.e.
localhost:8080/images/koala-1550238924102.jpg
and in your case you need to do this
localhost:8080/main.js
You can look in detail here.
app.use(express.static(__dirname + "/Public"));
app.use('controllers', express.static(__dirname + "/Controllers"));
Access files;
http://localhost:<port>/index.html
http://localhost:<port>/controllers/main.js
const publicStaticDirPath = path.join(__dirname, '../public');
app.use(express.static.(publicStaticDirPath));

Serving express static files issue

I am having issues w/ serving static files in my current Express app, although I've done a similar setup in a bunch of other apps.. My folder structure is as follows:
/rootfolder/
/app
package.json
/client
/dist
/static
index.html
/server
/src
index.js
Relevant part of my server/src/index.js:
app.use(express.static(path.join(__dirname, "client", "dist")));
Where __dirname = /rootfolder/app/server/src
And when the user hits the / endpoint:
app.get("/", (req, res) => {
res.sendFile(appRoot.path + "/client/dist/index.html");
});
Where appRoot.path = /rootfolder/app
When I hit the / endpoint, I get a status 200 with the following text:
/rootfolder/app/client/dist/index.html
From what I can tell, the files are coded relative to each other correctly.. Does anyone know what I might be doing wrong?
Thanks in advance!
You're using res.send() instead of res.sendFile()
Also I suggest resolving your path via the path module, instead of concatenating a string.
const path = require('path')
app.use(express.static(path.join(__dirname, 'client', 'dist', 'static')))
And for the response of /:
res.sendFile(path.join(__dirname, 'client', 'dist', 'index.html')))
Try
app.use(express.static(path.join(__dirname,'client','dist')));
It basically gets the root directory and combines it with /client+ /dist + /static to give you the full route, without being relative path.
Now Let's call rootdirectory/client/dist X. That is the main directory for static files
If you have other files that are static but not in the same folder, you will have to give relative path from the X directory
Example:
app.get('/',function(req,res){
res.sendFile('/static/data.txt');
}
In the example above you indicate that the static file(data.txt) is located in the X/static directory.
Therefore => rootDirectory/client/dist/static/data.txt
2nd Example:
Let's say you have a folder in dist called images which you want to only store images.
when you are giving routes, you MUST use /images/filename.extention

NodeJitsu error: Error: ENOENT, stat '/opt/run/snapshot/

My app’s folder structure for NodeJitsu is as follows (i.e., when i do a jitsu deploy, I'm in the folder that contains "server.js" - i.e., the "server" folder).
Root server
|___server.js
|___package.json
client
|___www
|___index.html
|___css
|___js
|___etc.
So at the root is the folder "server", containing the starting script, “server.js”. Then there’s a folder called “client”, parallel to "server", with a folder within that called “www”, and within “www” is the main “index.html”.
In my “server.js” file, I have the following code:
app.get(‘/’, function(req,res)
{
var aPath = path.resolve(“../client/www/”, “index.html”);
res.sendFile(aPath);
});
I don’t have a app.use(express.static(__dirname + '/somefolder'). And when I start the app, I get this error:
Error: ENOENT, stat '/opt/run/snapshot/client/www/index.html'
My process.cwd() is /opt/run/snapshot/package. Obviously the above path isn’t pointing to the location where “index.html” resides. But I thought the way I do the path.resolve(…) should point to “index.html”. I can’t see where the problem is. If “server.js” is in the root, then to get to “index.html”, which is in “client/www/index.html”, then I should need to write “../client/www”, relative to the excuting script, to get to “index.html”, right?.
Do you have any insights as to where the path is not set up correctly? What should /opt/run/snapshot/ be pointing to? Or, what changes do I need to make in the get(‘/’) handler to correctly point to my “index.html”?
EDIT
I incorrectly drew the folder structure. Now it's correct.
I also turned off the app.get() and turned on the app.use(express.static(__dirname + '/../client/www/'). But to no avail: now i get a Cannot GET / error.
What I'm ultimately after is to have the "server.js" file be the Node server that, mostly, just serves AngularJS HTML files to the browser, with attendant images, stylesheets, etc., from the "client" folder. This is the server's main role, with an additional role of authenticating the app's users, employing the very nice Satellizer module. And that's it. I have a MongoDB attached, but otherwise this is a very common and straightforward Node.js server app.
Thanks!
Try it without rooting, resolving and log out to double check:
// notice no leading / which is root. __dirname should be the dir of current file running
var staticPath = path.resolve(__dirname, '../client/www');
console.log(staticPath);
Then pass that into express.static
app.use(express.static(staticPath);
I would probably recommend following the layout and convention of express generated apps with app in the root and static files under public
/public
<static files>
app.js
Then do what the generated app does:
app.use(express.static(path.join(__dirname, 'public')));

Resources