The right way to upload JS files using HTML files through NodeJS

I cannot get the contents included in the chapter of the defualt.htm served page to "work". Html loads in dom, only CSS and JS files fail. Is there a better alternative? Id like to support the solution in NodeJS, but also openly for socket.io and express as well.

Thanks, below is what I use.

NodeJS Service Page

var http = require('http'), fs = require('fs'); fs.readFile(__dirname+'/default.htm', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(port.number); }); 

Default.html Page

 <!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="objects/css/site.css" type="text/css" /> <script src="objects/js/jquery.min.js" type="text/javascript"></script> <script src="objects/js/site.min.js" type="text/javascript"></script> </head> <body></body> </html> 
+4
source share
5 answers

I'm also going to drop my two cents.

The way I solved the same problem with serving static files is that I started using the Paperboy module, which is deprecated in favor of the submit module now.

Anyhoo, as I decided, it was a "grab" request before it went into my GET method and checked its path.

The way I “captured it” is as follows

 self.preProcess(self, request, response); 

and

 preProcess: function onRequest(app, request, response){ //DO STUFF } 

If the path contained the STATICFILES directory, I would do a different file submission, otherwise I would go with the "html" -path. Below is //DO STUFF the preProcess() function

 var path = urllib.parse(request.url).pathname; if(path.indexOf(settings.STATICFILES_DIR) != -1) { path = settings.STATICFILES_DIR; requestedFile = request.url.substring(request.url.lastIndexOf('/') + 1, request.url.length); return resolver.resolveResourceOr404(requestedFile, request, response); } 

There may be a better way to do this, but it works like a charm for the things I need for this.

Using the Paperboy module, I then using the function resolver.resolveResourceOr404(); deliver the file this way

 resolveResourceOr404 : function (filename, httpRequest, httpResponse) { var root = path.join(path.dirname(__filename), ''); paperboy.deliver(root, httpRequest, httpResponse) .error(function(e){ this.raise500(httpResponse); }) .otherwise(function(){ this.raise404(httpResponse); }); } 
+3
source

Your Javascript and styles do not work because they do not exist. Your current web server sends only one route - the root route. Instead, you will need to allow multiple routes. ExpressJS makes this easier for you, but still possible without it.

  var http = require('http'); var fs = require('fs'); var server = http.createServer(function(request, response){ var header_type = ""; var data = ""; var get = function (uri, callback) { // match `request.url` with uri with a regex or something. var regex = uri; if (request.url.match(regex)) { callback(); } }; var render = function (resource) { // resource = name of resource (ie index, site.min, jquery.min) fs.readFile( __dirname + "/" + resource, function(err, file) { if (err) return false; // Do something with the error.... header_type = ""; // Do some checking to find out what header type you must send. data = file; } }; get('/', function(req, res, next) { // Send out the index.html render('index.html'); next(); }); get('/javascript.min', function(req, res, next) { render('javascript.js'); next(); }); }); server.listen(8080); 

This may get you started, but you will have to implement some things, for example next() . Pretty simple solution, but working.

Another solution for responding to static files would be to create a catcher in the http.createServer . Within the get method, if uris does not match, you will search in the public folder corresponding to the full uri structure of the file system.

+4
source

Well, you serve your default.htm file in all requests. So, when the browser requests objects/js/jquery.min.js , your server returns the contents of default.htm .

You really should consider using express or some other structure.

+3
source

You better use Express for this kind of thing.

Something like this will do the job.

App.js

 var express = require('express') , http = require('http') , path = require('path'); var app = express(); //Configure Your App and Static Stuff Like Scripts Css app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); // Your view folder app.set('view engine', 'jade'); //Use jade as view template engine // app.set("view options", {layout: false}); // app.engine('html', require('ejs').renderFile); //Use ejs as view template engine app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(app.router); app.use(require('stylus').middleware(__dirname + '/public')); //Use Stylus as the CSS template engine app.use(express.static(path.join(__dirname, 'public'))); //This is the place for your static stuff }); app.get('/',function(req,res){ res.render('index.jade',{ title:"Index Page } }); 

An index is a jade pattern template. It turns into static html and works fine with expression.

For a global static header for all of your pages, you can create such a template and include it in any.

static_header.jade

  doctype 5 html head title= title script(src='/javascripts/jquery-1.8.2.min.js') block header link(rel='stylesheet', href='/stylesheets/style.css') body block content 

And finally, your index.jade, which uses static_header and its own dynamic header with its own scripts.

 extends static_header block header script(src='/javascripts/jquery-ui-1.9.1.custom.js') script(src='http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/jquery.ui.datepicker-tr.js') link(rel='stylesheet',href='/stylesheets/jquery-ui-1.9.1.custom.min.css') block content h1= title 

Put both files in the view folder and are ready to go.

+2
source

how about this:

 var http = require('http'); var fs = require('fs'); var path = require('path'); http.createServer(function (request, response) { console.log('request starting...'); var filePath = '.' + request.url; if (filePath == './') filePath = './index.html'; var extname = path.extname(filePath); var contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; case '.json': contentType = 'application/json'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpg'; break; case '.wav': contentType = 'audio/wav'; break; } fs.readFile(filePath, function(error, content) { if (error) { if(error.code == 'ENOENT'){ fs.readFile('./404.html', function(error, content) { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); }); } else { response.writeHead(500); response.end('Sorry, check with the site admin for error: '+error.code+' ..\n'); response.end(); } } else { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); } }); }).listen(8125); console.log('Server running at http://127.0.0.1:8125/'); 
+1
source

Source: https://habr.com/ru/post/1445446/


All Articles