1

I have several javascript files in my js directory. How can i add these files in nodeJS.

For example if I am to access a particular javascript file from a HTML document I use the following code :

<script src="js/main.js"></script>

But, how can I access this same file (js/main.js) in nodeJS ?

UPDATE

In NODE JS var express = require('express');

var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());

var urlencodedParser = bodyParser.urlencoded({ extended: false });
var jsonParser = bodyParser.json();
app.use(express.static(__dirname + '/public'));
require('js/main.js');

The error what i get:

Error: Cannot find module '/js/main.js'

3

2 Answers 2

4

In your server.js add following lines and check it once.

app.use(express.static(__dirname ));

this set your current directory as your root directory and put your js folder in root level. add comment if you don't find your answer.

Sign up to request clarification or add additional context in comments.

3 Comments

The JS files are in the folder PUBLIC/JS. I am still not able to find it
Then put following lines app.use(express.static(__dirname + '/public'));
remove require('js/main.js'); it is not required for load javascript in html
1

There should be 2 cases

1 - Include Javascript file in html file.

In this case, you can include your javascript file in your HTML file by writing the following code in your HTML File.

<script src="js/main.js"></script>

2 - Use One Javascript file code in other javascript file of your nodeJS server app code.

NodeJS has the concept of modules to write your code in multiple files.

You can export the code of main.js file as module with module.exports and use this code in any other js file by including following line

var mainModule = require('/path/main.js');

For more details about the modules in nodeJS, you can go through the documentation https://nodejs.org/api/modules.html

5 Comments

in main.js file. You need to export the module with
module.exports = ExportObject
Where ExportObject is the Object of main.js file what you want to use in other file and export it.
Also, Please take care of the path while importing the module.
If you are still facing the issue, Please post the directory structure and main.js file code. Will help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.