Fernando Ania Fernando Ania - 1 month ago 5
Node.js Question

Why can't node can't find the static directory?

I set up node so that it serves my public folder. Now I am trying to access the files in the public/data/event folder structure but it can't find it.

Here is my file structure
public/
data/
event/
src/
scripts/eventController.js
webserver.js


This my eventsController.js file. This file tries to access files in the public/data/event/ folder structure but can't find them.

'use strict';

let fs = require('fs');

module.exports.get = function(req, res) {
let event = fs.readFileSync('../public/data/event/' +
req.params.id + '.json', 'utf8');

res.setHeader('Content-Type', 'application/json');
res.send(event);
};

module.exports.save = function(req, res) {
let event = req.body;
fs.writeFileSync('../public/data/event/' + req.params.id +
'.json', JSON.stringify(event));

res.send(event);
};

module.exports.getAll = function(req, res) {
let path = '../public/data/event/';

let files = [];
try {
files = fs.readdirSync(path);
} catch (e) {
console.log(e);
res.send('[]');
res.end();
}
let results = '[';
for (let idx = 0; idx < files.length; idx++) {
if (files[idx].indexOf('.json') === files[idx].length - 5) {
results += fs.readFileSync(path + '/' + files[idx]) + ',';
}
}
results = results.substr(0, results.length - 1);
results += ']';

res.setHeader('Content-Type', 'application/json');
res.send(results);
res.end();
};


This is the webserver file, where I server the public folder

'use strict';

let express = require('express');

let port = process.env.PORT || 5000;

let path = require('path');
let app = express();
let events = require('./scripts/eventsController');
let rootPath = path.normalize(__dirname + '/../');
let bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static(rootPath + '/public'));
app.use('/bower_components', express.static(__dirname + '/../public/lib/'));
app.use("/public", express.static(path.join(__dirname, 'public')));

app.get('/data/event/:id', events.get);
app.get('/data/event', events.getAll);
app.post('/data/event/:id', events.save);

app.get('*', function(req, res) {
res.sendFile(rootPath + '/public/index.html');
});

app.listen(port, function(err) {
if (err) {
console.log('There was an error creating the system');
}
console.log('running server on port ' + port);
});


This is the error that I get from the terminal.enter image description here

Answer

It's because fs.readFile('public/data/event/') from src/scripts/eventController.js looks for the stuff in 'src/scripts/public/data/event/', not 'public/data/event'. You should go with fs.readFile('../../public/data/event'). Or better yet, always use absolute paths.