npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-mw-lang

v2.0.2

Published

Language-helper middleware for Express web server.

Downloads

21

Readme

express-mw-lang

Build Status codecov bitHound Overall Score bitHound Dependencies npm version npm downloads

Localization helper for Express web server.

Cuts off the language part from the path, and allow to use simple routes!

This middleware helps to determine the language, and handles urls of incoming requests for next middlewares. express-mw-lang does not use Accept-Language (but it is a good idea, to use the value of this HTTP-Header on first contact with the user, to predict his language).

To determine the language express-mw-lang uses only URL of the request. Expected format of the URL:

schema://host/< LANG >/path?params

Sample URL, handled in French:

https://example.net/fr/article/1

As you could see - lang is a first part of the path, and could be ommited, in this case the default language will be used.

Actually, express-mw-lang acts and is an express-router. The best practice is appending your router/routes (use/route/get/post/...) to the express-mw-lang, instead of habitual way with the Express-application itself.

See the Example section for more details.

Contributions are welcome!

Usage

Install:

$ npm install express-mw-lang

Configure and use in the app.js:

// ...
var langGen = require('express-mw-lang');
var app = express();

// ...

let langmw = langGen();
langmw.esu(app);

Example

"use strict";

var express         = require('express');
var logger          = require('morgan');          // just for example, not required
var bodyParser      = require('body-parser');     // just for example, not required
var langGen         = require('express-mw-lang');

var app = express();

app.use(logger());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// STEP 1: CREATING the middleware instance with options:
var langmw = langGen({
	defaultLanguage: 'en',
	availableLanguages: ['en', 'ru'],
});
// STEP 2: append middleware to application
// ( `esu` - is a reverse of `use`, because app and mw are swapped):
langmw.esu(app);


// appending main routes to the app (through lang-mw):
var router = express.Router();
router
	.route('/home')
	.get(function(req, res, next){
		res.status(200).send('Hello [' + req.lang.code + ']');
	});
// STEP 3: append your routes to lang-mw
langmw.use(router);

app.listen(3000, function() {
	console.log('Example app listening on port 3000!');
});

// http://192.168.1.68:3000/en/home
// -> Hello [en]
// http://192.168.1.68:3000/ru/home
// -> Hello [ru]
// http://192.168.1.68:3000/home
// -> Hello [en]

Options

const options = {
	defaultLanguage: 'en',
	availableLanguages: [],
	onLangDetected: function(langCode, req, res) {}
};

defaultLanguage

Default: 'en', string (ISO 639).

Default language

availableLanguages

Default: [], array of strings (each string - ISO 639 code).

Languages, which will be recognized by middleware.

  1. Default language is always available
  2. For requests to unavailable language the response will contain redirect to the / of the site.

onLangDetected

Defalt: null, function(langCode, req, res)

Callback, called when the lang is determined. Convenient place to setup the locale for momentjs or choosen i18n library.

Example

var i18n            = require("i18n")
var moment          = require('moment')

// ...

let options = {
	defaultLanguage: 'en',
	availableLanguages: ['en', 'ru'],
	onLangDetected: function(lang_code, req, res) {

		i18n.setLocale(lang_code)
		i18n.setLocale(req, lang_code)
		i18n.setLocale(res, lang_code)

		moment.locale(lang_code)
	}
}

req and res extensions

This middleware extends the req and res objects with a lang property, so extensions are:

  1. req.lang
  2. res.locals.lang

Further - description of the lang object.

defaultLanguage

string, default language, taken from options.

available

array of available options. Each item is an object with code-property (string, ISO 639)

usingDefault

bool indicates, that request is handled using default language (probably, there was an error, when the MW tried to determine the required language of the request).

routeTo

function(local_path, lang_code) , this function could help you to build paths to other pages of the site (taking the current language into account).

Notes about argument lang_code:

  1. it is optional
  2. UNKNOWN/UNAVAILABLE lang_code - cause to use the default lang
  3. NULL lang_code - cause to use CURRENT lang (determined by MW from URL)
  4. EMPTY ('') lang_code - cause to use default lang!!

Contributing

You could take part in the development process, just follow this guideline.

License

Please, read the LICENSE file in the root of the repository (or downloaded package).