Reputation: 659
I'm testing some code by using node express framework and ajax. I'm facing a problem that I get a 500 server error in the front-end side. Server-size nodejs code is like below(Very simple). This is the code for express router. Once I add some code about filesystem work like below, I get an 500 error. But, if I remove the line about readdirSync function call, it works well. I don't understand what in the world may cause this kind of problem. I know the synchronous function is not so good for here, but it's just some simple test.
router.post('/pictureListFromFile', function(req, res, next) {
var dirPath = "../public/img/laos1";
var fileList = [];
// fileList = fs.readdirSync(dirPath); // --> This code cause the problem.
console.log(fileList);
// response here for ajax
});
Upvotes: 0
Views: 1324
Reputation: 230
var fs = require('fs'); //if there is none
var fileList = [];
fileList.push(); //use push if you want to add to the array
But what causes the error in:
fs.readdirSync(dirPath);
is that dirPath is invalid. You have to use __dirname + path you need instead, or specify the correct path (C:/Program Files/...).
Upvotes: 1
Reputation: 3543
With readdirSync, as in most synchronous call in node, if there is an error, it will throw an error, crashing your server.
Never use synchronous call with node, the error management is based on try/catch and it do not scale well (it's actually freezing the entire node process).
Use the callback style :
fs.readdir(dirPath, function (err, files){
// rest of the code including res.send
});
Upvotes: 1