jeudi 19 février 2015

nodejs file system does not read file after first http response

i am making a simple http node.js server, by just making it send the most common files on web (HTML, JavaScript, CSS).


so i just make the node files and test for only HTML file which is just fine, but when i try to make it send JavaScript or CSS file, the server returns an error and closes.


main.js



/*
* Main node.js server file
*/

// Load all modules
console.log('Loading modules');
var http = require('http'),
fs = require('fs'),
file = require('./bin/file.js');

// Load config file
console.log('Loading configuration file');
var config = fs.readFileSync('./config.json');
var config = JSON.parse(config);

// Config http server
var host = http.createServer(function(request, response)
{
console.log('requesting: ', request.url);

var view = file.read(request.url);

response.writeHead(view.status, view.head);
response.write(view.content);
response.end();
});

// Start server
if(host.listen(config.port))
console.log('Http server initialized on port:', config.port);


just in case, config.json contains only the port and web files directory


file.js



// Load the required modules
var fs = require('fs');

// Load configuration
var config = fs.readFileSync('config.json');
var config = JSON.parse(config);

// Export module function
module.exports = {
read: function(file)
{
if(file == '/')
return loadFile('/index.html');
}
};

// Load the requested file
function loadFile(file)
{
var req = fs.readFileSync(config.dirFiles + file);

var result = {};

if(!req)
{
result = {
status: 404,
head: {'Content-Type': 'text/plain'},
content: 'The requested view does not exist'
};
}

else
{
result = {
status: 200,
head: {'Content-Type': getMIME(file)},
content: req
};
}

return result;
}

// Detect MIME file type
function getMIME(file)
{
var regex = /(.css|.html|.js)/;
var ext = regex.exec(file);

var MIME = '';

switch(ext[1])
{
case '.js':
MIME = 'text/javascript';
break;

case '.css':
MIME = 'text/css';
break;

case '.html':
MIME = 'text/html';
break;
}

return MIME;
}


on requesting a CSS file, the server tells that view.status property is undefined, this might be because the file is being read synchronous but i don't know what other way i would do


Aucun commentaire:

Enregistrer un commentaire