M
M
Mnwamnowich2015-06-11 04:36:14
JavaScript
Mnwamnowich, 2015-06-11 04:36:14

How to use variable in app.use(express.static(*))?

Hello. I'm trying to make a directory static, but the path to this directory is specified in the config.json file, the problem is that when I use the path to the directory directly, everything works:
app.use(express.static("template/main"));
But if I write the path to this directory into a variable, then I get an error "root path required
", here is the code itself:

fs.readFile('config.json', function (err, data) {
  if (err) throw err;
    config = JSON.parse(data);
    template = path.join("template", config.TemplateName);
    console.log(template);
});

app.use(express.static(template));

I read on the forums what needs to be app.use(express.static(template));replaced with app.use(express.static(__dirname+"/"+template));
There are no errors now, but there is no result either, the directory is not connected

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Sivkov, 2015-06-11
@Mnwamnowich

I think here the whole problem is in asynchronous initialization. Those. on idea in this place it is better to use fs.readFileSync.
Secondly, json can be imported as a regular module, without using fs:

var config = require('./config.json'),
    template = path.join(__dirname, "template", config.TemplateName);

console.log(template);
app.use(express.static(template));

_
_ _, 2015-06-11
@AMar4enko

Well, the file is read asynchronously, it's the basics.
Ask yourself the question, what will be executed first - the call to app.use or callback in readFile?
Replace readFile with readFileSync. Just remember that blocking calls should not be called anywhere except at the configuration stage.

D
Dimd13, 2015-06-11
@Dimd13

express.static has long been deprecated

var statics = require('serve-static');
...
app.use(statics(path.join(__dirname, 'public')));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question