简体   繁体   中英

nodejs how to execute other js file from index.js?

I want to create web app with nodejs but with structure like this

- modules
  | - module1
      | - module1.js
  | - module2
      | - module2.js
- index.js
- settings.js
  • First, i never use nodejs from scratch
  • Second, i know you will suggest using any other framework, sorry guys here i want to understand how nodejs and may be other nodejs framework works.
  • Third, this is for educational purpose

in modules/module1/module1.js :

res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Hello World aw!')

honestly i dont know how to code it properly, what i really want is i wanna execute that code and response to browser Hello World aw! from index.js :

router.get('/', function (req, res) {
  //in here i call modules/module1/module1.js, and execute the code
})

and how to do that properly? so it can run well

to load any script or module in nodejs you need to use require

like this

var module1 = require(__dirname + 'modules/module1/module1.js');

and then you can use module1 anywhere in your code

BTW for express you should create routes and then attach that routes to your app. See example below.

users.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

server.js

var express = require('express');
var app = express();
var users = require('./routes/users');
....
app.use('/users', users);

Every time with node when you need to have a module in a particular page you need to require this module.

example: you want to get the library express so at the top of your file who you want this library you do something like that.

var express = require('express');

Now you can use express in all the file. When this is a node library you just need to require the name.

this is the same thing with a file you create and you want inside a other one

var myfile = require('./../myfile');

with that you can use the word myfile inside all the file. But you need to figure out the path to this one.

A good links for read about this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM