1

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?

Kevin Hakanson
  • 41,386
  • 23
  • 126
  • 155
ldoc
  • 123
  • 2
  • 6

2 Answers2

3

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
Community
  • 1
  • 1
Kevin Hakanson
  • 41,386
  • 23
  • 126
  • 155
  • This is a good answer; this actually saved me when using `superagent` to test the text of .JS files retrieved from an Express static server, as `superagent` was not returning the text of the file unless it had UTF-8 encoding. – jrh Jan 02 '15 at 18:55
  • 1
    You can also get a slightly more expressive conditional using the Node.js `path` library. `var path = require('path'); if (path.extname(req.path) === '.js') { // it's JS }` – jrh Jan 02 '15 at 18:57
0

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>
asgoth
  • 35,552
  • 12
  • 89
  • 98