Last active
June 14, 2020 08:38
-
-
Save sscovil/656aef8301b11b370261d36a9b524521 to your computer and use it in GitHub Desktop.
Node Express server with i18next. Language files go in a `locales/` directory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"home": { | |
"title": "Hello World!" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"home": { | |
"title": "Hola Mundo!" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const express = require('express'); | |
const fs = require('fs'); | |
const i18n = require('i18next'); | |
const i18nFsBackend = require('i18next-node-fs-backend'); | |
const i18nMiddleware = require('i18next-express-middleware'); | |
const app = express(); | |
const port = process.env.PORT || 8080; | |
i18n | |
.use(i18nFsBackend) | |
.use(i18nMiddleware.LanguageDetector) | |
.init({ | |
backend: { | |
loadPath: __dirname + '/locales/{{lng}}.json', | |
addPath: __dirname + '/locales/{{lng}}.missing.json' | |
}, | |
fallbackLng: 'en', | |
lowerCaseLng: true, | |
preload: ['en', 'es'], | |
saveMissing: true | |
}); | |
app.use(i18nMiddleware.handle(i18n, { | |
removeLngFromUrl: false | |
})); | |
app.get('/', (req, res) => { | |
res.send(req.t('home.title')); | |
}); | |
module.exports = app.listen(port, (err) => { | |
if (err) { | |
console.log(err); | |
process.exit(1); | |
} else { | |
console.log(`Server is listening on port ${port}`); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "i18n-server", | |
"version": "1.0.0", | |
"description": "Node Express server with i18next.", | |
"main": "index.js", | |
"scripts": { | |
"start": "node index.js" | |
}, | |
"author": "Shaun Scovil <[email protected]>", | |
"license": "ISC", | |
"dependencies": { | |
"express": "4.15.2", | |
"i18next": "8.2.1", | |
"i18next-express-middleware": "1.0.5", | |
"i18next-node-fs-backend": "1.0.0" | |
} | |
} |
Was better if you add complete example.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thx bro :)