Expressjs my custom script file executes and then causes my server to 500

43 views Asked by At
var express = require('express');
var router = express.Router();

var root = "resources/"; //where the files will be stored

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index');
});
router.get('/exec', function(req, res){

  var value = req.query.script;  
  if(value){      
      var scriptsToRun = value.split(', ');   
      console.log(scriptsToRun);
      if(scriptsToRun){      
        for(var i = 0; i < scriptsToRun.length; i++){
          console.log(i);
          var thisScript = require(root + scriptsToRun[i]);
          thisScript(); //execute the script         
        }      
      }    
      console.log("All scripts run loaded:");
      console.log(scriptsToRun);
  }  
  res.render('index');  
});

module.exports = router;

And I the simple script just console logs 'hello'

console.log('hello!');

So now, when the query param matches the script in the /node_modules/resources folder, it executes (i get the log). but immediately after I get a 500 error. I have zero idea why.

Share your thoughts oh wise council.

1

There are 1 answers

0
robertklep On BEST ANSWER

Your simple script fails to export a function (or anything, for that matter), so thisScript will be undefined.

Instead, use this:

module.exports = function() {
  console.log('hello!');
};