accessing root public directory nodejs - javascript

Is there a way to access the root public directory without using ../../../ something like this. The below code works fine, but just thought the way i am accessing my public folder is bit messier.
router.get('/', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '../../public') });
});
Application structure:
/app
--node-modules
--public
--app //contains all angularjs related files
--assets //contains images and js libraries
--index.html
--server
--routes
--index.js //this holds all the route related code

On way is to use app-root-path. It is a module that helps you access your application's root path from anywhere in the application without resorting to relative paths.
var appRoot = require('app-root-path');
router.get('/', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, appRoot + '/public') });
});

Related

Serve an entire /directory using an express server

I have an express server, and I would like to provide route handling to manage an entire directory.
root
/html
/css
/js
/app.js
/images
/index.html
/some-other.html
/server.js
Do I need to serve every file individually using
app.get('/', (req, res) => {
res.send(htmlPath + '/index.html');
});
and adjust it for each .html file I am serving, or can I assign the /path-to-file as a variable and concatenate the variable into the htmlPath.
Additionally, is the following correct syntax to define the path/directory name
var htmlPath = path.join(__dirname, "html/");
app.use(express.static("html"));
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, "/html")));
I am relatively new and have been following various other questions and answers to get to where I am now.
according to SOLID principle and MCV structure, I suggest you to handle each part of your directory in an individual file.
root
/app
/statics
/images
/css
/views
/index.html
/some-other.html
/routes
/statics.js
/views.js
/index.js
/app.js
/server.js
so with this structure you have a routes directory which handle all the routes.
in the index.js(Routes) you send each request to the correct route file:
const staticsRouter = require('./statics');
const viewsRouter = require('./views');
module.exports = (app) => {
app.use('/statics',staticsRouterr);
app.use('/views',viewsRouter);
}
and in router files response to each request.

Multiple React apps on express

I have a server on express.js and there is a static folder in its root directory, it contains several react apps, something like this:
app:
static:
react1
react2
I am trying to make sure that when accessing the /react1 and /react2 addresses, the express will display the required application.
app.js:
app.use (express.static(path.join(__ dirname, "static")));
app.use ("/", indexRouter);
index.router:
router.get('/react1', (req, res) => {
res.sendFile(path.join (__dirname, '..', 'static', 'react1', 'index.html'))
});
router.get('/react2', (req, res) => {
res.sendFile(path.join (__dirname, '..', 'static', 'react2', 'index.html'))
});
When I try to navigate through these handles, I get a blank page. What am I doing wrong?
Your app.js & index.router looks fine.
You might wanna add * to the router.
For instance
router.get('/react1/*', (req, res) => {
I think the issue is in how the static content is built.
Make sure to add PUBLIC_URL to build script in package.json.
For instance: "build": "PUBLIC_URL=/admin react-scripts build",
You can refer this youtube video for a detailed explanation.

Express in NodeJS: URL param breaks routing

I'm trying to use express to serve my index.html, its dependancies as well as handle url params. For some reason, adding a URL param seems to break the pathing.
My basic nodeJS webapp has the following folder structure:
|- server.js (nodeJS server code)
|- public (dir)
| - app.js (app logic dependancy)
| - index.html (base HTML file to be served from server.js)
index.html is importing app.js as follows:
<script type="text/javascript" src="app.js"></script>
My express routes are as follows:
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/:country', (req, res) => {
res.sendFile(__dirname + '/index.html', {country:req.params.country});
}
I want the app to be served even when the country param is used.
However, when I add the URL param route, the above route stops working because express looks for index.html in the folder root, resulting in a 404.
Eg: http://localhost:3000/usa
Error: ENOENT: no such file or directory, stat '/Users/john/Projects/TestApp/index.html'
However, when I add the URL param route, the above route stops working because express looks for index.html in the folder root, resulting in a 404. Eg: http://localhost:3000/usa
Error: ENOENT: no such file or directory, stat '/Users/john/Projects/TestApp/index.html'
You should add public to the directory path, then.
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
Or, to work cross-platform:
const path = require("path")
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"))
})

I am not able to render static images while packaging node-express app using pkg

While trying to render an image from the public folder in my express app it is not rendering it.Can anyone help me how to configure the path so that I am able to render the images or css files in the public folder
while creating a executable file using pkg.
Attaching the code
app.use(express.static(Path.join(__dirname, 'public')));
app.get('/', function(req, res) {
console.log(Path.join(__dirname, 'public/images'));
res.render(Path.join(__dirname, 'views/' + 'testing'), {
variable: Path.join(__dirname, 'public/images/' + 'category.png')
});
});
app.listen(3003, function() {
console.log('listening port 3003');
});
https://www.npmjs.com/package/pkg#detecting-assets-in-source-code
Try to move a level up to the ../public directory in your file path if the express code is at the root level of a directory that is at the same level as the public directory. The path depends on where you are using app.use(express.static(publicDirectoryPath))
const publicDirectoryPath = path.join(__dirname, '../public');
app.use(express.static(publicDirectoryPath));

Scotch-io/node-todo app

How is the index.html (frontend Angular) getting called exactly?
In the tutorial, it was said that by having one of the following routes in route.js, frontend is getting called
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
----------or-------------------
app.get('*', function(req, res) {
res.sendfile('__dirname + '/public/index.html');
});
But even after removing that route, index.html is getting opened (or) If I rename index.html as index1.html at route and html file it is showing error.
Have you created a file index1.html in public folder? If yes, Use
res.sendfile('public/index1.html');
OR
var path = require('path');
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
to render index1.html.
Note : sendfile is deprecated.

Categories