Reputation: 1000
I'm running a node.js server. In the node I require and run the module by using
var h = require('h.js');
h.hello();
This prints Hello World to the console. However, I want to be able to run the code from h.js from a page(entrypage.html) in my browser as well. I try to import it by
<script type="text/javascript" src="/node_modules/h.js"></script>
However, this gives a 404 error when run on localhost.
GET http://localhost:8080/node_modules/h.js
How do I get access to this javascript file on the HTML page?
My file structure has a root with html/, js/, node_modules/ and server.js. The HTML page is inside html/, the js file in node_modules/
EDIT: I'm using the MEAN stack for this - MongoDB, Express.js, Angular.js and Node.js.
Upvotes: 0
Views: 1702
Reputation: 15292
first define path for your static resource which is your CSS,JS,Images etc.
app.use(express.static(path.join(__dirname, 'node_modules')));
then in html
<script type="text/javascript" src="h.js"></script>
NOTE : Try to avoid to use node_modules folder for source path of your static resources
Upvotes: 1
Reputation: 749
It should be possible to serve the file using express.static
(Example: app.use('/node_modules/', express.static(__dirname + '/node_modules/'));
), but I highly advise against serving node_modules and backend-specific files in the frontend!
Upvotes: 1
Reputation: 519
To be honest I'm not exactly sure what you're trying to achieve, I take it that you want to run the code in the browser just like running code in the node.js environment using require
to include packages like h.js from npm.
If that's what you want to do I would recommend using a tool like browserify or webpack which collects your code and puts it into a file which can then be used in a web browser.
Upvotes: 0