xaxa
xaxa

Reputation: 1159

Simple include file to node.js

I'm new to NodeJS, sorry for a simple question. I have a not-so big program, but want to make my main web.js file a bit more clear and create a few separate files (e.g. user_login.js, admin.js, etc) and simply paste these files' contents into web.js.

On the Internets everyone is advising to use require(), but that means writing a module - a self-consistent piece of code. But I need to simply include text of one file into another. Say, I would have

admin.js:

app.get('/admin', function (request, response)
{
    response.send("hey, you are an admin!");
});

user.js:

app.get('/', function (request, response)
{
    response.send("hi, how are you?");
}

web.js:

var express = require('express');
var app = express();

include('admin.js');
include('user.js');

Upvotes: 0

Views: 238

Answers (3)

Amberlamps
Amberlamps

Reputation: 40448

How about this:

admin.js

module.exports = function(app) {
    app.get('/admin', function(request, response) {
        response.send("hey, you are an admin!");
    });
}

web.js

var app = express();
require('./admin.js')(app);

I did not test it, so I might be wrong.

Upvotes: 2

mpm
mpm

Reputation: 20155

first:

// admin.js
var express=require('express')
var app=express();
app.get('/', function (request, response)
{
    response.send("hey, you are an admin!");
});

module.exports = app;

then:

// main.js
var express=require("express");
var app = express();
var admin=require("./admin");
app.use("/admin",admin.routes);

that's how node and express works. include "à la" PHP is an antipattern , and you should not even think about using that.

Upvotes: -1

gustavohenke
gustavohenke

Reputation: 41440

There's really no reason why you would need something like this.

Node has the built-in module vm, which can help you in your problem, but there will be a lot of more problems envolving using it.
For example: you'll need to pass a common context to your file, so it'll be able to require things at their own. This is very problematic, just write something that uses the standard module.exports from Node and forget this PHP thoughts :)

Upvotes: 0

Related Questions