Tuesday, 23 May 2017

Is there a way to pass a variable to a module from inside a http.createServer() function?

I have been learning node recently and have hit a bit of a road block.
I have stripped the code down quite a lot to make the question easier to read.
I hope you can help.

My folder structure below:

app
|
+--app.js
|
+--tester
|   |
|   +--data.json
|
+--modules
    |
    +--index.js

Whenever the the user is on a page that is not the root folder/homepage a test.html file is built. Inside the subfolders(i.e.tester) is a data.json file.

My main app.js file.

var fs = require('fs');
var http = require('http');
var path = require('path');
var index = require('./modules/index');

http.createServer(function(req,res){

  if(req.url != '/'){

    var currentURL = path.join(__dirname, req.url)

    res.writeHead(200,{"Content-Type":"text/html"});
    fs.writeFile(currentURL+"/test.html", "Hello World.", function(err){
      if(err){throw err};
    });

    res.end(currentURL);
  };

}).listen(3000);

I would like to access the data.json file located inside the tester folder from the index.js module.
I figured I would use the currentURL variable inside the index.js to access the json file.
I'm not sure how to do this.
I have googled and for the life of me, cannot find a solution. I'm probably thinking about it the wrong way.

Your help is much appreciated. Thanks, Moe



via Moe-Joe

No comments:

Post a Comment