Node.js public static folder to serve js with utf-8 charset - javascript

I´m using node.js and express to serve static JavaScript files to a single page application.
In the node.js server code I use express.static to allow public access folder
app.use(express.static(__dirname + '/public/'));
In the client side, I use $.getScript to get the JavaScript files stored in the public folder, for example:
$.getScript("js/init.js");
When I try to get some JavaScript files that have letters with accents or some UTF-8 special character I get strange characters instead of what I want.
Is there any way to set the charset when I define the public folder?

An answer from What's the simplest way to serve static files using node.js? gave me the hint of inserting your own middleware before static.
The code below finds *.js files and sets the charset to utf-8.
app.use(function(req, res, next) {
if (/.*\.js/.test(req.path)) {
res.charset = "utf-8";
}
next();
});
app.use(express.static(__dirname + '/public/'));
After doing this, look for the following response header.
Content-Type: application/javascript; charset=utf-8

In your html pages there has to be the same encoding as the encoding of your resource files (or the other way around)
Make sure you set a meta tag in the head section:
<meta charset='utf-8'></meta>

Related

Local path referencing when using jQuery.getJSON() method in javascript [duplicate]

I'm running a local copy of nodejs and have taken some code which runs a web service and references a local index.html on startup. This service is running locally on my desktop.
I've been playing about with CSS, and have found no matter what I do, the style sheet does not load, taking the configuration from the style sheet and dropping this within some <style> elements works fine. But for some reason or another, it's not reading the stylesheet.
Location of style sheet is: c:\program files\nodejs\default.css
HTML code:
<link rel="stylesheet" type="text/css" href="default.css" />
This is in the same location as index.js, index.html. Has permissions etc to read file.
Any ideas why this potentially may not be loading.
index.js code:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res){
fs.readFile('index.html', function (err, data){
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length' : data.length
});
res.write(data);
res.end();
});
}).listen(1337, '127.0.0.1');
Your server:
http.createServer(function (req, res){
fs.readFile('index.html'
… is configured to ignore everything in the request and always return the contents of index.html.
So when the browser requests the stylesheet it is given index.html.
You need to pay attention to the path (which will be in the request) and serve up appropriate content (which for serving up static files means mapping it onto the file system, determining if the file exists or not, then loading that file or a 404 message), with the appropriate content type (so you'd need to determine that for each kind of file), and status code.
This is a significant chunk of work and not worth reinventing the wheel over so it would probably be best done by finding a static file serving module (Google turns up node-static) for Node (or replacing Node with something like Lighttpd or Apache HTTPD).
If you want to serve up dynamic content as well as static content, then Express is a popular choice (and has support for static files).

Having all website paths load the same static website in express

In my express server, I want to have all paths load the same static website, which I tried doing with the following code:
const express = require('express');
const app = express();
app.use('*', express.static('build'));
app.listen(3000);
Unfortunately I am presented with the following console errors when I navigate to any path on localhost:
:3000/main.js/:1 Uncaught SyntaxError: Unexpected token <
When attempting to view the JS file with the error, it seems to be serving index.html in its place.
I know this is due to the wildcard, but I can't think of a way to cleanly exclude all file names and paths from the static server.
I think you're looking for something a little more like this..app.use(express.static('public')
if your tree looks like
ProjectName
| server.js
| public
| index.html
you don't need the * as a parameter since setting the express.static sets the folder open to public view. This is how you separate your server code and client code. Be careful not to expose your entire project directory as people will then have access to your server code. This is why you're client files should be kept in a public folder or a www folder (common practices)
--EDIT
//this will server css, and js files so they can be linked into the html
app.use(express.static(__dirname + '/public'));
//this will force all url's except the public files to be given the index.html file.
app.use('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});

How to send a lot of files from server to client using express (NodeJS)

I'm trying to send files from NodeJS server to clients. Many images, css files, js files. For a few files I use
app.get('/js/client.js', function (req, res) {
res.sendFile(path.join(__dirname, '/', 'client.js'));
});
The path is var path = require('path');
So, if I use this construction for every file I want to send, this part of the code will be huge. How can I simplify it?
If you want to serve static content, put all content in public folder in will be automatically served using express.
app.use(express.static( __dirname + "/public"));

exclude a folder from expressjs routing

On my expressjs app, public assets are loaded in this way:
app.use(express.static(__dirname + '/public'));
And then I redirect all requests to the index, to handle every path with Backbone
app.get('*', routes.index);
Why the /public folder is redirect too?
Also if i try to add '/public' as a first argument, it doesn't work:
app.use('/public', express.static(__dirname + '/public'));
For anyone who get any problem related to static files serving:
Before evaluating possible solutions to the problem, be sure to define express.static before the app.use(app.router).
I found lots of examples online: sometimes its defined below, sometimes not.
Putting it first solved all my problems.
app.use(express.static(path.join(__dirname + '/public')))
app.use(app.router)
After you placed the static router before app.router, express will attempt to serve requests first by matching a file from the static folder (public), if there's no match, it will pass it to routes.index as the following rule matches everything;
app.get('*', routes.index);
Also, to match any file from public dir, you need not use /public/ in the request url.
For example to fetch public/images/icon.png or public/js/scripts.js, you will only need to access /images/icon.png or /js/scripts.js. If you invoke a /public request, it will not match anything in static dir, and pass the request on to routes.index.
Hope it helps.

Requesting a file with node.js server

This is the root of the app (http://site.com), that runs when requesting the domain. If I wanted to add only one file say robots.txt (http://site.com/robots.txt) to be requested using this http server, how would I do that? It would pull from the contents of robots.txt and echo it out.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('homepage');
res.end('');
}).listen(process.env.VMC_APP_PORT || 1337, null);
Thanks
Instead of implementing such a functionality manually, you can build your application with http://expressjs.com/ framework and use static middleware documented at http://expressjs.com/guide.html to server static files. But I would personally prefer to put Nginx in front of Node to serve static file, because it has proven to be efficient for this job and it is all about configuration rather than programming then. Configuration can be different depending on the specific purpose and environment, but mine is documented at http://skovalyov.blogspot.com/2012/07/deploy-multiple-node-applications-on.html

Categories

Resources