我设置了节点,以便它为我的公共文件夹服务。现在我正在尝试访问public / data / event文件夹结构中的文件,但找不到它。
Here is my file structure
public/
data/
event/
src/
scripts/eventController.js
webserver.js
这是我的eventsController.js文件。此文件尝试访问public / data / event /文件夹结构中的文件,但无法找到它们。
'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();
};
这是webserver文件,我在那里服务公用文件夹
'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);
});
答案 0 :(得分:1)
这是因为来自src / scripts / eventController.js的fs.readFile('public / data / event /')在'src / scripts / public / data / event /'中查找内容,而不是'public / data /事件'。你应该使用fs.readFile('../../ public / data / event')。或者更好的是,始终使用绝对路径。
答案 1 :(得分:0)
public
文件夹是src
文件夹的兄弟。你需要一个绝对路径(即从root开始。例如/ home / username / proj / node / public /)或正确的相对路径,即../public