I'm a begginer so sorry if the question seems stupid but I'm developping a NodeJs server and I'm currently using this (in backend/server.js) to have my public files :
app.use(express.static(Path.join(__dirname, '..', 'public')));
But I would like to know if I can add a package of a node module in my paths like :
app.use(express.static(Path.join(__dirname, '..', 'node_modules/fuelsdk-node')));
My directory is set like this :
How should I import my node module ? Can I use both at the same time ? Or do I have to do it an other way? Thanks !
It is NOT recommended to call static files from the node_modules folder directly. Instead, a good practice is to use redirections. Idea is to have a link that will call a static resource from the node_modules folder.
app.use("link", "physical address");
in your case, it will be something like:
app.use("/", express.static(Path.join(__dirname, '..', 'public')));
app.use("/fuelsdk-node", express.static(Path.join(__dirname, '..', 'node_modules/fuelsdk-node')));
Now you can call your static files by relevant to the link.
For better understanding please see an example of usage bootstrap from node_modules
npm install jquery
npm install bootstrap
server.js file
// grab express
var express = require("express");
// create an express app
var app = express();
// CONFIGURE THE APP
// ==================================================
// tell node where to look for site resources
app.use('/', express.static(__dirname + '/public'));
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect JS bootstrap
app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jquery
// create an express route for a homepage
// http://localhost:8080/
app.get('/', function(req, res){
res.sendfile('/index.html');
});
app.listen(8080);
console.log('Server has started');
public/index.html
<!DOCTYPE html>
<html>
<head>
<title>Static Files</title>
<link rel='stylesheet' href='/css/bootstrap.min.css' />
<script type="text/javascript" src="/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
</head>
<body>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>It works</strong> Static files from node_modules. css & javascript are connected by redirected link
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<script type="text/javascript">
$('.alert').alert();
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With