Shruti Dengre
Shruti Dengre

Reputation: 19

how to run different .js file in one server.js file in NODE JS?

this is demo.js file and i want to use this file in server.js file so that i can use diffrent js files in one server file.

Demo.js:

    app.get('/add User', function (req, res) {
    var MongoClient = mongodb.MongoClient;
    var url = 'mongodb://localhost:27017/project';
    MongoClient.connect(url, function (err, db) {
             var collection = db.collection('users');
            collection.find({name: 'shruti'}).toArray(function (err, result) {
                console.log(, result);
                    db.close();
        });

Server.js:

    var a = require('./demo.js');
    vr http=require("http");

    var server = http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/html"});
      response.write(a);
      res.end();});
    server.listen(7860);

Upvotes: 1

Views: 766

Answers (2)

Stacey Mulcahy
Stacey Mulcahy

Reputation: 41

As stated, you need to export. When you do:

var item = require("mymodule");

Require returns an object, which is a reference the value of module.exports for that given file - in your case demo.js.

You can write your modules a few ways as some people have shown you. Because it is encapsulated you basically are identifying what is public or can be called. Few ways to write it - you could also do:

module.exports = {
  yourCall: function () {
     console.log("stuff here");
  }
};

As stated by @ishann, who is dead on here, you are writing something you assume might be populated. Going to a database and returning is an asynchronous call - so it will take time to go do that and then for the results to be returned.

Based on your structure - ideally what you want to do is assign the route ( "/addUser" ) which will pass in the response object to you:

app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
         var collection = db.collection('users');
        collection.find({name: 'shruti'}).toArray(function (err, result) {
            console.log(, result);
                db.close(); 
                 // set the type
                 res.writeHead(200, {"Content-Type": "application/json"});
                 res.write(result);

    });

Just looks like your code needs a bit of reorg, but separting concerns is good. You might want to also check out Express as a framework for node.

Upvotes: 0

coding_idiot
coding_idiot

Reputation: 13734

A possible sample would look like :

demo.js

var myModule = {
  defineRoutes: function(router){
    //do something...
  }
}

module.exports = myModule;

server.js

var myModule = require('demo.js');
myModule.defineRoutes(router);

Upvotes: 1

Related Questions