Answer the question
In order to leave comments, you need to log in
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));
app.use(express.static(template));
replaced with app.use(express.static(__dirname+"/"+template));
Answer the question
In order to leave comments, you need to log in
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));
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question