From 1fd61c668706d6b8db884aa07321538422c318a8 Mon Sep 17 00:00:00 2001 From: Douglas Christopher Wilson Date: Mon, 14 Feb 2022 21:49:02 -0500 Subject: [PATCH] lint: use es6 everywhere besides legacy api docs closes #470 --- _includes/api/en/5x/app-all.md | 2 +- _includes/api/en/5x/app-delete-method.md | 2 +- _includes/api/en/5x/app-get-method.md | 2 +- _includes/api/en/5x/app-mountpath.md | 6 +- _includes/api/en/5x/app-onmount.md | 4 +- _includes/api/en/5x/app-param.md | 16 ++--- _includes/api/en/5x/app-post-method.md | 2 +- _includes/api/en/5x/app-put-method.md | 2 +- _includes/api/en/5x/app-render.md | 4 +- _includes/api/en/5x/app-route.md | 6 +- _includes/api/en/5x/app-router.md | 2 +- _includes/api/en/5x/app-settings.md | 4 +- _includes/api/en/5x/app-use.md | 42 ++++++------- _includes/api/en/5x/app.md | 2 +- _includes/api/en/5x/express.static.md | 2 +- _includes/api/en/5x/req-app.md | 4 +- _includes/api/en/5x/req-baseUrl.md | 2 +- _includes/api/en/5x/req-body.md | 2 +- _includes/api/en/5x/req-originalUrl.md | 2 +- _includes/api/en/5x/req-range.md | 2 +- _includes/api/en/5x/req-route.md | 2 +- _includes/api/en/5x/req.md | 8 +-- _includes/api/en/5x/res-download.md | 2 +- _includes/api/en/5x/res-format.md | 14 ++--- _includes/api/en/5x/res-headersSent.md | 2 +- _includes/api/en/5x/res-locals.md | 2 +- _includes/api/en/5x/res-render.md | 4 +- _includes/api/en/5x/res-sendFile.md | 10 ++-- _includes/api/en/5x/res.md | 8 +-- _includes/api/en/5x/router-METHOD.md | 12 ++-- _includes/api/en/5x/router-param.md | 24 ++++---- _includes/api/en/5x/router-route.md | 14 ++--- _includes/api/en/5x/router-use.md | 16 ++--- _includes/api/en/5x/router.md | 4 +- en/advanced/developing-template-engines.md | 10 ++-- en/guide/behind-proxies.md | 2 +- en/guide/database-integration.md | 70 +++++++++++----------- en/guide/error-handling.md | 28 ++++----- en/guide/migrating-4.md | 22 +++---- en/guide/overriding-express-api.md | 2 +- en/guide/routing.md | 50 ++++++++-------- en/guide/using-middleware.md | 44 +++++++------- en/guide/using-template-engines.md | 2 +- en/guide/writing-middleware.md | 10 ++-- en/starter/basic-routing.md | 8 +-- en/starter/faq.md | 4 +- ja/advanced/developing-template-engines.md | 10 ++-- ja/guide/behind-proxies.md | 2 +- ja/guide/database-integration.md | 68 ++++++++++----------- ja/guide/error-handling.md | 26 ++++---- ja/guide/migrating-4.md | 22 +++---- ja/guide/routing.md | 50 ++++++++-------- ja/guide/using-middleware.md | 42 ++++++------- ja/guide/using-template-engines.md | 2 +- ja/guide/writing-middleware.md | 8 +-- ko/advanced/developing-template-engines.md | 10 ++-- package.json | 28 ++++----- th/advanced/developing-template-engines.md | 10 ++-- th/guide/behind-proxies.md | 2 +- th/guide/database-integration.md | 64 ++++++++++---------- th/guide/error-handling.md | 10 ++-- th/guide/migrating-4.md | 22 +++---- th/guide/routing.md | 50 ++++++++-------- th/guide/using-middleware.md | 42 ++++++------- th/guide/using-template-engines.md | 2 +- th/guide/writing-middleware.md | 8 +-- th/starter/basic-routing.md | 8 +-- th/starter/faq.md | 4 +- tr/advanced/developing-template-engines.md | 10 ++-- tr/guide/behind-proxies.md | 2 +- tr/guide/database-integration.md | 68 ++++++++++----------- tr/guide/error-handling.md | 28 ++++----- tr/guide/migrating-4.md | 22 +++---- tr/guide/overriding-express-api.md | 2 +- tr/guide/routing.md | 50 ++++++++-------- tr/guide/using-middleware.md | 44 +++++++------- tr/guide/using-template-engines.md | 2 +- tr/guide/writing-middleware.md | 10 ++-- tr/starter/basic-routing.md | 8 +-- tr/starter/faq.md | 4 +- zh-cn/guide/database-integration.md | 68 ++++++++++----------- 81 files changed, 645 insertions(+), 647 deletions(-) diff --git a/_includes/api/en/5x/app-all.md b/_includes/api/en/5x/app-all.md index 9830c1cffe..fd0b9ea43d 100644 --- a/_includes/api/en/5x/app-all.md +++ b/_includes/api/en/5x/app-all.md @@ -11,7 +11,7 @@ The following callback is executed for requests to `/secret` whether using GET, POST, PUT, DELETE, or any other HTTP request method: ```js -app.all('/secret', function (req, res, next) { +app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') next() // pass control to the next handler }) diff --git a/_includes/api/en/5x/app-delete-method.md b/_includes/api/en/5x/app-delete-method.md index f0102b46ef..d7a3a42158 100644 --- a/_includes/api/en/5x/app-delete-method.md +++ b/_includes/api/en/5x/app-delete-method.md @@ -8,7 +8,7 @@ For more information, see the [routing guide](/guide/routing.html). #### Example ```js -app.delete('/', function (req, res) { +app.delete('/', (req, res) => { res.send('DELETE request to homepage') }) ``` diff --git a/_includes/api/en/5x/app-get-method.md b/_includes/api/en/5x/app-get-method.md index c8077f8e25..5bc5df871a 100644 --- a/_includes/api/en/5x/app-get-method.md +++ b/_includes/api/en/5x/app-get-method.md @@ -9,7 +9,7 @@ For more information, see the [routing guide](/guide/routing.html). #### Example ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('GET request to homepage') }) ``` diff --git a/_includes/api/en/5x/app-mountpath.md b/_includes/api/en/5x/app-mountpath.md index 6f8f8a73b4..5a41877f71 100644 --- a/_includes/api/en/5x/app-mountpath.md +++ b/_includes/api/en/5x/app-mountpath.md @@ -12,7 +12,7 @@ const express = require('express') const app = express() // the main app const admin = express() // the sub app -admin.get('/', function (req, res) { +admin.get('/', (req, res) => { console.log(admin.mountpath) // /admin res.send('Admin Homepage') }) @@ -29,13 +29,13 @@ patterns it is mounted on, as shown in the following example. ```js const admin = express() -admin.get('/', function (req, res) { +admin.get('/', (req, res) => { console.log(admin.mountpath) // [ '/adm*n', '/manager' ] res.send('Admin Homepage') }) const secret = express() -secret.get('/', function (req, res) { +secret.get('/', (req, res) => { console.log(secret.mountpath) // /secr*t res.send('Admin Secret') }) diff --git a/_includes/api/en/5x/app-onmount.md b/_includes/api/en/5x/app-onmount.md index 46b2faebf4..d7c831d786 100644 --- a/_includes/api/en/5x/app-onmount.md +++ b/_includes/api/en/5x/app-onmount.md @@ -16,12 +16,12 @@ For details, see [Application settings](/en/5x/api.html#app.settings.table). ```js const admin = express() -admin.on('mount', function (parent) { +admin.on('mount', (parent) => { console.log('Admin Mounted') console.log(parent) // refers to the parent app }) -admin.get('/', function (req, res) { +admin.get('/', (req, res) => { res.send('Admin Homepage') }) diff --git a/_includes/api/en/5x/app-param.md b/_includes/api/en/5x/app-param.md index d85b98da02..dd8b1ad970 100644 --- a/_includes/api/en/5x/app-param.md +++ b/_includes/api/en/5x/app-param.md @@ -7,9 +7,9 @@ If `name` is an array, the `callback` trigger is registered for each parameter d For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. ```js -app.param('user', function (req, res, next, id) { +app.param('user', (req, res, next, id) => { // try to get the user details from the User model and attach it to the request object - User.find(id, function (err, user) { + User.find(id, (err, user) => { if (err) { next(err) } else if (user) { @@ -27,17 +27,17 @@ Param callback functions are local to the router on which they are defined. They All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. ```js -app.param('id', function (req, res, next, id) { +app.param('id', (req, res, next, id) => { console.log('CALLED ONLY ONCE') next() }) -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { console.log('although this matches') next() }) -app.get('/user/:id', function (req, res) { +app.get('/user/:id', (req, res) => { console.log('and this matches too') res.end() }) @@ -52,17 +52,17 @@ and this matches too ``` ```js -app.param(['id', 'page'], function (req, res, next, value) { +app.param(['id', 'page'], (req, res, next, value) => { console.log('CALLED ONLY ONCE with', value) next() }) -app.get('/user/:id/:page', function (req, res, next) { +app.get('/user/:id/:page', (req, res, next) => { console.log('although this matches') next() }) -app.get('/user/:id/:page', function (req, res) { +app.get('/user/:id/:page', (req, res) => { console.log('and this matches too') res.end() }) diff --git a/_includes/api/en/5x/app-post-method.md b/_includes/api/en/5x/app-post-method.md index 667e8a817b..60efbcbdda 100644 --- a/_includes/api/en/5x/app-post-method.md +++ b/_includes/api/en/5x/app-post-method.md @@ -8,7 +8,7 @@ For more information, see the [routing guide](/guide/routing.html). #### Example ```js -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('POST request to homepage') }) ``` diff --git a/_includes/api/en/5x/app-put-method.md b/_includes/api/en/5x/app-put-method.md index 99e119dad0..0575714854 100644 --- a/_includes/api/en/5x/app-put-method.md +++ b/_includes/api/en/5x/app-put-method.md @@ -7,7 +7,7 @@ Routes HTTP PUT requests to the specified path with the specified callback funct #### Example ```js -app.put('/', function (req, res) { +app.put('/', (req, res) => { res.send('PUT request to homepage') }) ``` diff --git a/_includes/api/en/5x/app-render.md b/_includes/api/en/5x/app-render.md index ca5b016db8..1a40d0f210 100644 --- a/_includes/api/en/5x/app-render.md +++ b/_includes/api/en/5x/app-render.md @@ -15,11 +15,11 @@ cache view during development; view caching is enabled in production by default. ```js -app.render('email', function (err, html) { +app.render('email', (err, html) => { // ... }) -app.render('email', { name: 'Tobi' }, function (err, html) { +app.render('email', { name: 'Tobi' }, (err, html) => { // ... }) ``` diff --git a/_includes/api/en/5x/app-route.md b/_includes/api/en/5x/app-route.md index 44c714eb03..2a0db757dd 100644 --- a/_includes/api/en/5x/app-route.md +++ b/_includes/api/en/5x/app-route.md @@ -7,14 +7,14 @@ Use `app.route()` to avoid duplicate route names (and thus typo errors). const app = express() app.route('/events') - .all(function (req, res, next) { + .all((req, res, next) => { // runs for all HTTP verbs first // think of it as route specific middleware! }) - .get(function (req, res, next) { + .get((req, res, next) => { res.json({}) }) - .post(function (req, res, next) { + .post((req, res, next) => { // maybe add a new event... }) ``` diff --git a/_includes/api/en/5x/app-router.md b/_includes/api/en/5x/app-router.md index 5462456752..b821faa75d 100644 --- a/_includes/api/en/5x/app-router.md +++ b/_includes/api/en/5x/app-router.md @@ -7,7 +7,7 @@ const express = require('express') const app = express() const router = app.router -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('hello world') }) diff --git a/_includes/api/en/5x/app-settings.md b/_includes/api/en/5x/app-settings.md index 4eee7b0c73..4bd9150447 100644 --- a/_includes/api/en/5x/app-settings.md +++ b/_includes/api/en/5x/app-settings.md @@ -263,7 +263,7 @@ app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) Custom trust implementation. Use this only if you know what you are doing. ```js -app.set('trust proxy', function (ip) { +app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs else return false }) @@ -308,7 +308,7 @@ The [express.static](#express.static) middleware ignores these settings. Custom ETag function implementation. Use this only if you know what you are doing. ```js -app.set('etag', function (body, encoding) { +app.set('etag', (body, encoding) => { return generateHash(body, encoding) // consider the function is defined }) ``` diff --git a/_includes/api/en/5x/app-use.md b/_includes/api/en/5x/app-use.md index 5c382dad67..09bc253c3f 100644 --- a/_includes/api/en/5x/app-use.md +++ b/_includes/api/en/5x/app-use.md @@ -16,7 +16,7 @@ Since `path` defaults to "/", middleware mounted without a path will be executed For example, this middleware function will be executed for _every_ request to the app: ```js -app.use(function (req, res, next) { +app.use((req, res, next) => { console.log('Time: %d', Date.now()) next() }) @@ -37,12 +37,12 @@ Middleware functions are executed sequentially, therefore the order of middlewar ```js // this middleware will not allow the request to go beyond it -app.use(function (req, res, next) { +app.use((req, res, next) => { res.send('Hello World') }) // requests will never reach this route -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Welcome') }) ``` @@ -54,7 +54,7 @@ Error-handling middleware always takes _four_ arguments. You must provide four Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`): ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) @@ -83,7 +83,7 @@ mounting middleware. This will match paths starting with `/abcd`: ```js -app.use('/abcd', function (req, res, next) { +app.use('/abcd', (req, res, next) => { next() }) ``` @@ -97,7 +97,7 @@ app.use('/abcd', function (req, res, next) { This will match paths starting with `/abcd` and `/abd`: ```js -app.use('/abc?d', function (req, res, next) { +app.use('/abc?d', (req, res, next) => { next() }) ``` @@ -105,7 +105,7 @@ app.use('/abc?d', function (req, res, next) { This will match paths starting with `/abcd`, `/abbcd`, `/abbbbbcd`, and so on: ```js -app.use('/ab+cd', function (req, res, next) { +app.use('/ab+cd', (req, res, next) => { next() }) ``` @@ -113,7 +113,7 @@ app.use('/ab+cd', function (req, res, next) { This will match paths starting with `/abcd`, `/abxcd`, `/abFOOcd`, `/abbArcd`, and so on: ```js -app.use('/ab*cd', function (req, res, next) { +app.use('/ab*cd', (req, res, next) => { next() }) ``` @@ -121,7 +121,7 @@ app.use('/ab*cd', function (req, res, next) { This will match paths starting with `/ad` and `/abcd`: ```js -app.use('/a(bc)?d', function (req, res, next) { +app.use('/a(bc)?d', (req, res, next) => { next() }) ``` @@ -135,7 +135,7 @@ app.use('/a(bc)?d', function (req, res, next) { This will match paths starting with `/abc` and `/xyz`: ```js -app.use(/\/abc|\/xyz/, function (req, res, next) { +app.use(/\/abc|\/xyz/, (req, res, next) => { next() }) ``` @@ -149,7 +149,7 @@ app.use(/\/abc|\/xyz/, function (req, res, next) { This will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`: ```js -app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) { +app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req, res, next) => { next() }) ``` @@ -184,7 +184,7 @@ Even though the examples are for `app.use()`, they are also valid for `app.use() You can define and mount a middleware function locally. ```js -app.use(function (req, res, next) { +app.use((req, res, next) => { next() }) ``` @@ -193,7 +193,7 @@ A router is valid middleware. ```js const router = express.Router() -router.get('/', function (req, res, next) { +router.get('/', (req, res, next) => { next() }) app.use(router) @@ -202,7 +202,7 @@ app.use(router) An Express app is valid middleware. ```js const subApp = express() -subApp.get('/', function (req, res, next) { +subApp.get('/', (req, res, next) => { next() }) app.use(subApp) @@ -218,12 +218,12 @@ You can specify more than one middleware function at the same mount path. ```js const r1 = express.Router() -r1.get('/', function (req, res, next) { +r1.get('/', (req, res, next) => { next() }) const r2 = express.Router() -r2.get('/', function (req, res, next) { +r2.get('/', (req, res, next) => { next() }) @@ -240,12 +240,12 @@ Use an array to group middleware logically. ```js const r1 = express.Router() -r1.get('/', function (req, res, next) { +r1.get('/', (req, res, next) => { next() }) const r2 = express.Router() -r2.get('/', function (req, res, next) { +r2.get('/', (req, res, next) => { next() }) @@ -265,13 +265,13 @@ function mw1 (req, res, next) { next() } function mw2 (req, res, next) { next() } const r1 = express.Router() -r1.get('/', function (req, res, next) { next() }) +r1.get('/', (req, res, next) => { next() }) const r2 = express.Router() -r2.get('/', function (req, res, next) { next() }) +r2.get('/', (req, res, next) => { next() }) const subApp = express() -subApp.get('/', function (req, res, next) { next() }) +subApp.get('/', (req, res, next) => { next() }) app.use(mw1, [mw2, r1, r2], subApp) ``` diff --git a/_includes/api/en/5x/app.md b/_includes/api/en/5x/app.md index 6cf41903a1..458ba8a447 100644 --- a/_includes/api/en/5x/app.md +++ b/_includes/api/en/5x/app.md @@ -7,7 +7,7 @@ Create it by calling the top-level `express()` function exported by the Express const express = require('express') const app = express() -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('hello world') }) diff --git a/_includes/api/en/5x/express.static.md b/_includes/api/en/5x/express.static.md index 3d1df52884..d1c0d5b44d 100644 --- a/_includes/api/en/5x/express.static.md +++ b/_includes/api/en/5x/express.static.md @@ -79,7 +79,7 @@ const options = { index: false, maxAge: '1d', redirect: false, - setHeaders: function (res, path, stat) { + setHeaders (res, path, stat) { res.set('x-timestamp', Date.now()) } } diff --git a/_includes/api/en/5x/req-app.md b/_includes/api/en/5x/req-app.md index 8fde7da97e..30873d7ab7 100644 --- a/_includes/api/en/5x/req-app.md +++ b/_includes/api/en/5x/req-app.md @@ -14,7 +14,7 @@ app.get('/viewdirectory', require('./mymiddleware.js')) ```js // mymiddleware.js -module.exports = function (req, res) { - res.send('The views directory is ' + req.app.get('views')) +module.exports = (req, res) => { + res.send(`The views directory is ${req.app.get('views')}`) } ``` diff --git a/_includes/api/en/5x/req-baseUrl.md b/_includes/api/en/5x/req-baseUrl.md index 98b18c6894..0f16e75d79 100644 --- a/_includes/api/en/5x/req-baseUrl.md +++ b/_includes/api/en/5x/req-baseUrl.md @@ -10,7 +10,7 @@ For example: ```js const greet = express.Router() -greet.get('/jp', function (req, res) { +greet.get('/jp', (req, res) => { console.log(req.baseUrl) // /greet res.send('Konichiwa!') }) diff --git a/_includes/api/en/5x/req-body.md b/_includes/api/en/5x/req-body.md index 4c26d0d4df..591d8991e5 100644 --- a/_includes/api/en/5x/req-body.md +++ b/_includes/api/en/5x/req-body.md @@ -19,7 +19,7 @@ const upload = multer() // for parsing multipart/form-data app.use(bodyParser.json()) // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded -app.post('/profile', upload.array(), function (req, res, next) { +app.post('/profile', upload.array(), (req, res, next) => { console.log(req.body) res.json(req.body) }) diff --git a/_includes/api/en/5x/req-originalUrl.md b/_includes/api/en/5x/req-originalUrl.md index b47f015c5c..660f46d7b1 100644 --- a/_includes/api/en/5x/req-originalUrl.md +++ b/_includes/api/en/5x/req-originalUrl.md @@ -19,7 +19,7 @@ combination of `req.baseUrl` and `req.url`. Consider following example: ```js // GET 'http://www.example.com/admin/new?sort=desc' -app.use('/admin', function (req, res, next) { +app.use('/admin', (req, res, next) => { console.dir(req.originalUrl) // '/admin/new?sort=desc' console.dir(req.baseUrl) // '/admin' console.dir(req.path) // '/new' diff --git a/_includes/api/en/5x/req-range.md b/_includes/api/en/5x/req-range.md index 898c82b5de..8ebce46382 100644 --- a/_includes/api/en/5x/req-range.md +++ b/_includes/api/en/5x/req-range.md @@ -22,7 +22,7 @@ const range = req.range(1000) // the type of the range if (range.type === 'bytes') { // the ranges - range.forEach(function (r) { + range.forEach((r) => { // do something with r.start and r.end }) } diff --git a/_includes/api/en/5x/req-route.md b/_includes/api/en/5x/req-route.md index bc5bc31a0b..ab8fe50fc7 100644 --- a/_includes/api/en/5x/req-route.md +++ b/_includes/api/en/5x/req-route.md @@ -3,7 +3,7 @@ Contains the currently-matched route, a string. For example: ```js -app.get('/user/:id?', function userIdHandler (req, res) { +app.get('/user/:id?', (req, res) => { console.log(req.route) res.send('GET') }) diff --git a/_includes/api/en/5x/req.md b/_includes/api/en/5x/req.md index ad29486da3..ce78da8a4c 100644 --- a/_includes/api/en/5x/req.md +++ b/_includes/api/en/5x/req.md @@ -8,16 +8,16 @@ by the parameters to the callback function in which you're working. For example: ```js -app.get('/user/:id', function (req, res) { - res.send('user ' + req.params.id) +app.get('/user/:id', (req, res) => { + res.send(`user ${req.params.id}`) }) ``` But you could just as well have: ```js -app.get('/user/:id', function (request, response) { - response.send('user ' + request.params.id) +app.get('/user/:id', (request, response) => { + response.send(`user ${request.params.id}`) }) ``` diff --git a/_includes/api/en/5x/res-download.md b/_includes/api/en/5x/res-download.md index 08bc64e08a..de19c5d041 100644 --- a/_includes/api/en/5x/res-download.md +++ b/_includes/api/en/5x/res-download.md @@ -19,7 +19,7 @@ res.download('/report-12345.pdf') res.download('/report-12345.pdf', 'report.pdf') -res.download('/report-12345.pdf', 'report.pdf', function (err) { +res.download('/report-12345.pdf', 'report.pdf', (err) => { if (err) { // Handle error, but keep in mind the response may be partially-sent // so check res.headersSent diff --git a/_includes/api/en/5x/res-format.md b/_includes/api/en/5x/res-format.md index 476a2caea7..e33e008b48 100644 --- a/_includes/api/en/5x/res-format.md +++ b/_includes/api/en/5x/res-format.md @@ -13,19 +13,19 @@ to "application/json" or "\*/json" (however if it is "\*/\*", then the response ```js res.format({ - 'text/plain': function () { + 'text/plain' () { res.send('hey') }, - 'text/html': function () { + 'text/html' () { res.send('

hey

') }, - 'application/json': function () { + 'application/json' () { res.send({ message: 'hey' }) }, - default: function () { + default () { // log the request and respond with 406 res.status(406).send('Not Acceptable') } @@ -37,15 +37,15 @@ to these types for a slightly less verbose implementation: ```js res.format({ - text: function () { + text () { res.send('hey') }, - html: function () { + html () { res.send('

hey

') }, - json: function () { + json () { res.send({ message: 'hey' }) } }) diff --git a/_includes/api/en/5x/res-headersSent.md b/_includes/api/en/5x/res-headersSent.md index 6f31d92ac6..1bbe06d1b3 100644 --- a/_includes/api/en/5x/res-headersSent.md +++ b/_includes/api/en/5x/res-headersSent.md @@ -3,7 +3,7 @@ Boolean property that indicates if the app sent HTTP headers for the response. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { console.log(res.headersSent) // false res.send('OK') console.log(res.headersSent) // true diff --git a/_includes/api/en/5x/res-locals.md b/_includes/api/en/5x/res-locals.md index a21dac1568..80b346eb14 100644 --- a/_includes/api/en/5x/res-locals.md +++ b/_includes/api/en/5x/res-locals.md @@ -8,7 +8,7 @@ This property is useful for exposing request-level information such as the reque authenticated user, user settings, and so on. ```js -app.use(function (req, res, next) { +app.use((req, res, next) => { res.locals.user = req.user res.locals.authenticated = !req.user.anonymous next() diff --git a/_includes/api/en/5x/res-render.md b/_includes/api/en/5x/res-render.md index c6d25168e8..437481aeb3 100644 --- a/_includes/api/en/5x/res-render.md +++ b/_includes/api/en/5x/res-render.md @@ -22,12 +22,12 @@ to cache the view during development; view caching is enabled in production by d res.render('index') // if a callback is specified, the rendered HTML string has to be sent explicitly -res.render('index', function (err, html) { +res.render('index', (err, html) => { res.send(html) }) // pass a local variable to the view -res.render('user', { name: 'Tobi' }, function (err, html) { +res.render('user', { name: 'Tobi' }, (err, html) => { // ... }) ``` diff --git a/_includes/api/en/5x/res-sendFile.md b/_includes/api/en/5x/res-sendFile.md index 902e292c05..e415a21dc6 100644 --- a/_includes/api/en/5x/res-sendFile.md +++ b/_includes/api/en/5x/res-sendFile.md @@ -43,7 +43,7 @@ ending the request-response cycle, or by passing control to the next route. Here is an example of using `res.sendFile` with all its arguments. ```js -app.get('/file/:name', function (req, res, next) { +app.get('/file/:name', (req, res, next) => { const options = { root: path.join(__dirname, 'public'), dotfiles: 'deny', @@ -54,7 +54,7 @@ app.get('/file/:name', function (req, res, next) { } const fileName = req.params.name - res.sendFile(fileName, options, function (err) { + res.sendFile(fileName, options, (err) => { if (err) { next(err) } else { @@ -68,13 +68,13 @@ The following example illustrates using `res.sendFile` to provide fine-grained support for serving files: ```js -app.get('/user/:uid/photos/:file', function (req, res) { +app.get('/user/:uid/photos/:file', (req, res) => { const uid = req.params.uid const file = req.params.file - req.user.mayViewFilesFrom(uid, function (yes) { + req.user.mayViewFilesFrom(uid, (yes) => { if (yes) { - res.sendFile('/uploads/' + uid + '/' + file) + res.sendFile(`/uploads/${uid}/${file}`) } else { res.status(403).send("Sorry! You can't see that.") } diff --git a/_includes/api/en/5x/res.md b/_includes/api/en/5x/res.md index 127d7eac2f..a26c2c7d14 100644 --- a/_includes/api/en/5x/res.md +++ b/_includes/api/en/5x/res.md @@ -9,16 +9,16 @@ by the parameters to the callback function in which you're working. For example: ```js -app.get('/user/:id', function (req, res) { - res.send('user ' + req.params.id) +app.get('/user/:id', (req, res) => { + res.send(`user ${req.params.id}`) }) ``` But you could just as well have: ```js -app.get('/user/:id', function (request, response) { - response.send('user ' + request.params.id) +app.get('/user/:id', (request, response) => { + response.send(`user ${request.params.id}`) }) ``` diff --git a/_includes/api/en/5x/router-METHOD.md b/_includes/api/en/5x/router-METHOD.md index 512bf63f4a..657ccf2190 100644 --- a/_includes/api/en/5x/router-METHOD.md +++ b/_includes/api/en/5x/router-METHOD.md @@ -24,7 +24,7 @@ these matches, for example "GET /" would match the following route, as would "GET /?name=tobi". ```js -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('hello world') }) ``` @@ -34,10 +34,10 @@ constraints, for example the following would match "GET /commits/71dbb9c" as wel as "GET /commits/71dbb9c..4c084f9". ```js -router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) { +router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req, res) => { const from = req.params[0] const to = req.params[1] || 'HEAD' - res.send('commit range ' + from + '..' + to) + res.send(`commit range ${from}..${to}`) }) ``` @@ -53,13 +53,13 @@ function fn (req, res, next) { console.log('I come here') next('router') } -router.get('/foo', fn, function (req, res, next) { +router.get('/foo', fn, (req, res, next) => { console.log('I dont come here') }) -router.get('/foo', function (req, res, next) { +router.get('/foo', (req, res, next) => { console.log('I dont come here') }) -app.get('/foo', function (req, res) { +app.get('/foo', (req, res) => { console.log(' I come here too') res.end('good') }) diff --git a/_includes/api/en/5x/router-param.md b/_includes/api/en/5x/router-param.md index e46c7e6f0d..aaa1c6d610 100644 --- a/_includes/api/en/5x/router-param.md +++ b/_includes/api/en/5x/router-param.md @@ -17,9 +17,9 @@ Unlike `app.param()`, `router.param()` does not accept an array of route paramet For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. ```js -router.param('user', function (req, res, next, id) { +router.param('user', (req, res, next, id) => { // try to get the user details from the User model and attach it to the request object - User.find(id, function (err, user) { + User.find(id, (err, user) => { if (err) { next(err) } else if (user) { @@ -37,17 +37,17 @@ Param callback functions are local to the router on which they are defined. They A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. ```js -router.param('id', function (req, res, next, id) { +router.param('id', (req, res, next, id) => { console.log('CALLED ONLY ONCE') next() }) -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { console.log('although this matches') next() }) -router.get('/user/:id', function (req, res) { +router.get('/user/:id', (req, res) => { console.log('and this matches too') res.end() }) @@ -79,8 +79,8 @@ const app = express() const router = express.Router() // customizing the behavior of router.param() -router.param(function (param, option) { - return function (req, res, next, val) { +router.param((param, option) => { + return (req, res, next, val) => { if (val === option) { next() } else { @@ -93,13 +93,13 @@ router.param(function (param, option) { router.param('id', 1337) // route to trigger the capture -router.get('/user/:id', function (req, res) { +router.get('/user/:id', (req, res) => { res.send('OK') }) app.use(router) -app.listen(3000, function () { +app.listen(3000, () => { console.log('Ready') }) ``` @@ -107,8 +107,8 @@ app.listen(3000, function () { In this example, the `router.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id. ```js -router.param(function (param, validator) { - return function (req, res, next, val) { +router.param((param, validator) => { + return (req, res, next, val) => { if (validator(val)) { next() } else { @@ -117,7 +117,7 @@ router.param(function (param, validator) { } }) -router.param('id', function (candidate) { +router.param('id', (candidate) => { return !isNaN(parseFloat(candidate)) && isFinite(candidate) }) ``` diff --git a/_includes/api/en/5x/router-route.md b/_includes/api/en/5x/router-route.md index 7fc8ab0faf..a3a7ff936c 100644 --- a/_includes/api/en/5x/router-route.md +++ b/_includes/api/en/5x/router-route.md @@ -10,34 +10,34 @@ Building on the `router.param()` example above, the following code shows how to ```js const router = express.Router() -router.param('user_id', function (req, res, next, id) { +router.param('user_id', (req, res, next, id) => { // sample user, would actually fetch from DB, etc... req.user = { - id: id, + id, name: 'TJ' } next() }) router.route('/users/:user_id') - .all(function (req, res, next) { + .all((req, res, next) => { // runs for all HTTP verbs first // think of it as route specific middleware! next() }) - .get(function (req, res, next) { + .get((req, res, next) => { res.json(req.user) }) - .put(function (req, res, next) { + .put((req, res, next) => { // just an example of maybe updating the user req.user.name = req.params.name // save user ... etc res.json(req.user) }) - .post(function (req, res, next) { + .post((req, res, next) => { next(new Error('not implemented')) }) - .delete(function (req, res, next) { + .delete((req, res, next) => { next(new Error('not implemented')) }) ``` diff --git a/_includes/api/en/5x/router-use.md b/_includes/api/en/5x/router-use.md index 303a160005..f0c5decf0b 100644 --- a/_includes/api/en/5x/router-use.md +++ b/_includes/api/en/5x/router-use.md @@ -15,19 +15,19 @@ const router = express.Router() // simple logger for this router's requests // all requests to this router will first hit this middleware -router.use(function (req, res, next) { +router.use((req, res, next) => { console.log('%s %s %s', req.method, req.url, req.path) next() }) // this will only be invoked if the path starts with /bar from the mount point -router.use('/bar', function (req, res, next) { +router.use('/bar', (req, res, next) => { // ... maybe some additional /bar logging ... next() }) // always invoked -router.use(function (req, res, next) { +router.use((req, res, next) => { res.send('Hello World') }) @@ -49,7 +49,7 @@ const logger = require('morgan') router.use(logger()) router.use(express.static(path.join(__dirname, 'public'))) -router.use(function (req, res) { +router.use((req, res) => { res.send('Hello') }) ``` @@ -61,7 +61,7 @@ before adding the logger middleware: ```js router.use(express.static(path.join(__dirname, 'public'))) router.use(logger()) -router.use(function (req, res) { +router.use((req, res) => { res.send('Hello') }) ``` @@ -89,13 +89,13 @@ const openRouter = express.Router() authRouter.use(require('./authenticate').basic(usersdb)) -authRouter.get('/:user_id/edit', function (req, res, next) { +authRouter.get('/:user_id/edit', (req, res, next) => { // ... Edit user UI ... }) -openRouter.get('/', function (req, res, next) { +openRouter.get('/', (req, res, next) => { // ... List users ... }) -openRouter.get('/:user_id', function (req, res, next) { +openRouter.get('/:user_id', (req, res, next) => { // ... View user ... }) diff --git a/_includes/api/en/5x/router.md b/_includes/api/en/5x/router.md index 0581c34baf..ec33782c53 100644 --- a/_includes/api/en/5x/router.md +++ b/_includes/api/en/5x/router.md @@ -15,14 +15,14 @@ and so on) to it just like an application. For example: ```js // invoked for any requests passed to this router -router.use(function (req, res, next) { +router.use((req, res, next) => { // .. some logic here .. like any other middleware next() }) // will handle any request that ends in /events // depends on where the router is "use()'d" -router.get('/events', function (req, res, next) { +router.get('/events', (req, res, next) => { // .. }) ``` diff --git a/en/advanced/developing-template-engines.md b/en/advanced/developing-template-engines.md index 7e0880a006..6cf96c16b0 100755 --- a/en/advanced/developing-template-engines.md +++ b/en/advanced/developing-template-engines.md @@ -14,13 +14,13 @@ The following code is an example of implementing a very simple template engine f ```js const fs = require('fs') // this engine requires the fs module -app.engine('ntl', function (filePath, options, callback) { // define the template engine - fs.readFile(filePath, function (err, content) { +app.engine('ntl', (filePath, options, callback) => { // define the template engine + fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine const rendered = content.toString() - .replace('#title#', '' + options.title + '') - .replace('#message#', '

' + options.message + '

') + .replace('#title#', `${options.title}`) + .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) }) @@ -37,7 +37,7 @@ Your app will now be able to render `.ntl` files. Create a file named `index.ntl Then, create the following route in your app. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/en/guide/behind-proxies.md b/en/guide/behind-proxies.md index a1d14a7b3f..b645093e1e 100755 --- a/en/guide/behind-proxies.md +++ b/en/guide/behind-proxies.md @@ -67,7 +67,7 @@ When using this setting, it is important to ensure there are not multiple, diffe Custom trust implementation. ```js -app.set('trust proxy', function (ip) { +app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs else return false }) diff --git a/en/guide/database-integration.md b/en/guide/database-integration.md index 05313d3c81..7af24f618c 100644 --- a/en/guide/database-integration.md +++ b/en/guide/database-integration.md @@ -44,7 +44,7 @@ $ npm install cassandra-driver const cassandra = require('cassandra-driver') const client = new cassandra.Client({ contactPoints: ['localhost'] }) -client.execute('select key from system.local', function (err, result) { +client.execute('select key from system.local', (err, result) => { if (err) throw err console.log(result.rows[0]) }) @@ -67,7 +67,7 @@ const couchbase = require('couchbase') const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // add a document to a bucket -bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) { +bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err) } else { @@ -78,7 +78,7 @@ bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, res // get all documents with shoe size 13 const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' const query = N1qlQuery.fromString(n1ql) -bucket.query(query, [13], function (err, result) { +bucket.query(query, [13], (err, result) => { if (err) { console.log(err) } else { @@ -105,7 +105,7 @@ nano.db.create('books') const books = nano.db.use('books') // Insert a book document in the books database -books.insert({ name: 'The Art of war' }, null, function (err, body) { +books.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err) } else { @@ -114,7 +114,7 @@ books.insert({ name: 'The Art of war' }, null, function (err, body) { }) // Get a list of all books -books.list(function (err, body) { +books.list((err, body) => { if (err) { console.log(err) } else { @@ -139,13 +139,13 @@ $ npm install level levelup leveldown const levelup = require('levelup') const db = levelup('./mydb') -db.put('name', 'LevelUP', function (err) { +db.put('name', 'LevelUP', (err) => { if (err) return console.log('Ooops!', err) - db.get('name', function (err, value) { + db.get('name', (err, value) => { if (err) return console.log('Ooops!', err) - console.log('name=' + value) + console.log(`name=${value}`) }) }) ``` @@ -173,7 +173,7 @@ const connection = mysql.createConnection({ connection.connect() -connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => { if (err) throw err console.log('The solution is: ', rows[0].solution) @@ -197,10 +197,10 @@ $ npm install mongodb ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { if (err) throw err - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -213,12 +213,12 @@ MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { if (err) throw err const db = client.db('animals') - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -247,12 +247,12 @@ const driver = neo4j.driver('neo4j://localhost:7687', neo4j.auth.basic('neo4j', const session = driver.session() -session.readTransaction(function (tx) { +session.readTransaction((tx) => { return tx.run('MATCH (n) RETURN count(n) AS count') - .then(function (res) { + .then((res) => { console.log(res.records[0].get('count')) }) - .catch(function (error) { + .catch((error) => { console.log(error) }) }) @@ -321,10 +321,10 @@ const pgp = require('pg-promise')(/* options */) const db = pgp('postgres://username:password@host:port/database') db.one('SELECT $1 AS value', 123) - .then(function (data) { + .then((data) => { console.log('DATA:', data.value) }) - .catch(function (error) { + .catch((error) => { console.log('ERROR:', error) }) ``` @@ -345,19 +345,19 @@ $ npm install redis const redis = require('redis') const client = redis.createClient() -client.on('error', function (err) { - console.log('Error ' + err) +client.on('error', (err) => { + console.log(`Error ${err}`) }) client.set('string key', 'string val', redis.print) client.hset('hash key', 'hashtest 1', 'some value', redis.print) client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) -client.hkeys('hash key', function (err, replies) { - console.log(replies.length + ' replies:') +client.hkeys('hash key', (err, replies) => { + console.log(`${replies.length} replies:`) - replies.forEach(function (reply, i) { - console.log(' ' + i + ': ' + reply) + replies.forEach((reply, i) => { + console.log(` ${i}: ${reply}`) }) client.quit() @@ -393,7 +393,7 @@ const config = { const connection = new Connection(config) -connection.on('connect', function (err) { +connection.on('connect', (err) => { if (err) { console.log(err) } else { @@ -402,17 +402,17 @@ connection.on('connect', function (err) { }) function executeStatement () { - request = new Request("select 123, 'hello world'", function (err, rowCount) { + request = new Request("select 123, 'hello world'", (err, rowCount) => { if (err) { console.log(err) } else { - console.log(rowCount + ' rows') + console.log(`${rowCount} rows`) } connection.close() }) - request.on('row', function (columns) { - columns.forEach(function (column) { + request.on('row', (columns) => { + columns.forEach((column) => { if (column.value === null) { console.log('NULL') } else { @@ -441,18 +441,18 @@ $ npm install sqlite3 const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database(':memory:') -db.serialize(function () { +db.serialize(() => { db.run('CREATE TABLE lorem (info TEXT)') const stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (let i = 0; i < 10; i++) { - stmt.run('Ipsum ' + i) + stmt.run(`Ipsum ${i}`) } stmt.finalize() - db.each('SELECT rowid AS id, info FROM lorem', function (err, row) { - console.log(row.id + ': ' + row.info) + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) }) }) @@ -488,9 +488,9 @@ client.search({ } } } -}).then(function (response) { +}).then((response) => { const hits = response.hits.hits -}, function (error) { +}, (error) => { console.trace(error.message) }) ``` diff --git a/en/guide/error-handling.md b/en/guide/error-handling.md index 97538be847..87728e525b 100755 --- a/en/guide/error-handling.md +++ b/en/guide/error-handling.md @@ -21,7 +21,7 @@ require no extra work. If synchronous code throws an error, then Express will catch and process it. For example: ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { throw new Error('BROKEN') // Express will catch this on its own. }) ``` @@ -31,8 +31,8 @@ and middleware, you must pass them to the `next()` function, where Express will catch and process them. For example: ```js -app.get('/', function (req, res, next) { - fs.readFile('/file-does-not-exist', function (err, data) { +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { if (err) { next(err) // Pass errors to Express. } else { @@ -47,7 +47,7 @@ will call `next(value)` automatically when they reject or throw an error. For example: ```js -app.get('/user/:id', async function (req, res, next) { +app.get('/user/:id', async (req, res, next) => { const user = await getUserById(req.params.id) res.send(user) }) @@ -83,8 +83,8 @@ You must catch errors that occur in asynchronous code invoked by route handlers middleware and pass them to Express for processing. For example: ```js -app.get('/', function (req, res, next) { - setTimeout(function () { +app.get('/', (req, res, next) => { + setTimeout(() => { try { throw new Error('BROKEN') } catch (err) { @@ -103,8 +103,8 @@ Use promises to avoid the overhead of the `try...catch` block or when using func that return promises. For example: ```js -app.get('/', function (req, res, next) { - Promise.resolve().then(function () { +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { throw new Error('BROKEN') }).catch(next) // Errors will be passed to Express. }) @@ -121,7 +121,7 @@ catching, by reducing the asynchronous code to something trivial. For example: ```js app.get('/', [ function (req, res, next) { - fs.readFile('/maybe-valid-file', 'utf-8', function (err, data) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { res.locals.data = data next(err) }) @@ -196,7 +196,7 @@ except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example: ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) @@ -213,7 +213,7 @@ app.use(bodyParser.urlencoded({ })) app.use(bodyParser.json()) app.use(methodOverride()) -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { // logic }) ``` @@ -276,15 +276,15 @@ If you have a route handler with multiple callback functions you can use the `ro ```js app.get('/a_route_behind_paywall', - function checkIfPaidSubscriber (req, res, next) { + (req, res, next) => { if (!req.user.hasPaid) { // continue handling this request next('route') } else { next() } - }, function getPaidContent (req, res, next) { - PaidContent.find(function (err, doc) { + }, (req, res, next) => { + PaidContent.find((err, doc) => { if (err) return next(err) res.json(doc) }) diff --git a/en/guide/migrating-4.md b/en/guide/migrating-4.md index d35244bc8f..7ff159c14a 100755 --- a/en/guide/migrating-4.md +++ b/en/guide/migrating-4.md @@ -100,7 +100,7 @@ In version 4 you can use a variable parameter to define the path where middlewar For example: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) @@ -130,13 +130,13 @@ Here is an example of chained route handlers that are defined by using the `app. ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -159,16 +159,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -350,7 +350,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -478,7 +478,7 @@ if (app.get('env') === 'development') { } var server = http.createServer(app) -server.listen(app.get('port'), function () { +server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -487,7 +487,7 @@ server.listen(app.get('port'), function () { Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -588,7 +588,7 @@ delete the line that says `module.exports = app;` at the end of the ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` diff --git a/en/guide/overriding-express-api.md b/en/guide/overriding-express-api.md index bf2a912540..86895e86b9 100644 --- a/en/guide/overriding-express-api.md +++ b/en/guide/overriding-express-api.md @@ -55,7 +55,7 @@ The following code rewrites how the value of `req.ip` is to be derived. Now, it Object.defineProperty(app.request, 'ip', { configurable: true, enumerable: true, - get: function () { return this.get('Client-IP') } + get () { return this.get('Client-IP') } }) ``` diff --git a/en/guide/routing.md b/en/guide/routing.md index a43a6a4621..26080c828c 100755 --- a/en/guide/routing.md +++ b/en/guide/routing.md @@ -29,7 +29,7 @@ const express = require('express') const app = express() // respond with "hello world" when a GET request is made to the homepage -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('hello world') }) ``` @@ -42,12 +42,12 @@ The following code is an example of routes that are defined for the GET and the ```js // GET method route -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('GET request to the homepage') }) // POST method route -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('POST request to the homepage') }) ``` @@ -58,7 +58,7 @@ For a full list, see [app.METHOD](/{{ page.lang }}/4x/api.html#app.METHOD). There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route "/secret" whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods). ```js -app.all('/secret', function (req, res, next) { +app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') next() // pass control to the next handler }) @@ -85,7 +85,7 @@ Here are some examples of route paths based on strings. This route path will match requests to the root route, `/`. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('root') }) ``` @@ -93,7 +93,7 @@ app.get('/', function (req, res) { This route path will match requests to `/about`. ```js -app.get('/about', function (req, res) { +app.get('/about', (req, res) => { res.send('about') }) ``` @@ -101,7 +101,7 @@ app.get('/about', function (req, res) { This route path will match requests to `/random.text`. ```js -app.get('/random.text', function (req, res) { +app.get('/random.text', (req, res) => { res.send('random.text') }) ``` @@ -111,7 +111,7 @@ Here are some examples of route paths based on string patterns. This route path will match `acd` and `abcd`. ```js -app.get('/ab?cd', function (req, res) { +app.get('/ab?cd', (req, res) => { res.send('ab?cd') }) ``` @@ -119,7 +119,7 @@ app.get('/ab?cd', function (req, res) { This route path will match `abcd`, `abbcd`, `abbbcd`, and so on. ```js -app.get('/ab+cd', function (req, res) { +app.get('/ab+cd', (req, res) => { res.send('ab+cd') }) ``` @@ -127,7 +127,7 @@ app.get('/ab+cd', function (req, res) { This route path will match `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd`, and so on. ```js -app.get('/ab*cd', function (req, res) { +app.get('/ab*cd', (req, res) => { res.send('ab*cd') }) ``` @@ -135,7 +135,7 @@ app.get('/ab*cd', function (req, res) { This route path will match `/abe` and `/abcde`. ```js -app.get('/ab(cd)?e', function (req, res) { +app.get('/ab(cd)?e', (req, res) => { res.send('ab(cd)?e') }) ``` @@ -145,7 +145,7 @@ Examples of route paths based on regular expressions: This route path will match anything with an "a" in it. ```js -app.get(/a/, function (req, res) { +app.get(/a/, (req, res) => { res.send('/a/') }) ``` @@ -153,7 +153,7 @@ app.get(/a/, function (req, res) { This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonflyman`, and so on. ```js -app.get(/.*fly$/, function (req, res) { +app.get(/.*fly$/, (req, res) => { res.send('/.*fly$/') }) ``` @@ -171,7 +171,7 @@ req.params: { "userId": "34", "bookId": "8989" } To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. ```js -app.get('/users/:userId/books/:bookId', function (req, res) { +app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params) }) ``` @@ -219,7 +219,7 @@ Route handlers can be in the form of a function, an array of functions, or combi A single callback function can handle a route. For example: ```js -app.get('/example/a', function (req, res) { +app.get('/example/a', (req, res) => { res.send('Hello from A!') }) ``` @@ -227,10 +227,10 @@ app.get('/example/a', function (req, res) { More than one callback function can handle a route (make sure you specify the `next` object). For example: ```js -app.get('/example/b', function (req, res, next) { +app.get('/example/b', (req, res, next) => { console.log('the response will be sent by the next function ...') next() -}, function (req, res) { +}, (req, res) => { res.send('Hello from B!') }) ``` @@ -268,10 +268,10 @@ const cb1 = function (req, res, next) { next() } -app.get('/example/d', [cb0, cb1], function (req, res, next) { +app.get('/example/d', [cb0, cb1], (req, res, next) => { console.log('the response will be sent by the next function ...') next() -}, function (req, res) { +}, (req, res) => { res.send('Hello from D!') }) ``` @@ -301,13 +301,13 @@ Here is an example of chained route handlers that are defined by using `app.rout ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -325,16 +325,16 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) diff --git a/en/guide/using-middleware.md b/en/guide/using-middleware.md index 9a13db8cc9..64c0b05f65 100644 --- a/en/guide/using-middleware.md +++ b/en/guide/using-middleware.md @@ -41,7 +41,7 @@ This example shows a middleware function with no mount path. The function is exe const express = require('express') const app = express() -app.use(function (req, res, next) { +app.use((req, res, next) => { console.log('Time:', Date.now()) next() }) @@ -51,7 +51,7 @@ This example shows a middleware function mounted on the `/user/:id` path. The fu HTTP request on the `/user/:id` path. ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -60,7 +60,7 @@ app.use('/user/:id', function (req, res, next) { This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.send('USER') }) ``` @@ -69,10 +69,10 @@ Here is an example of loading a series of middleware functions at a mount point, It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path. ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -83,15 +83,15 @@ Route handlers enable you to define multiple routes for a path. The example belo This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { console.log('ID:', req.params.id) next() -}, function (req, res, next) { +}, (req, res, next) => { res.send('User Info') }) // handler for the /user/:id path, which prints the user ID -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.send(req.params.id) }) ``` @@ -102,18 +102,18 @@ To skip the rest of the middleware functions from a router middleware stack, cal This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack else next() -}, function (req, res, next) { +}, (req, res, next) => { // send a regular response res.send('regular') }) // handler for the /user/:id path, which sends a special response -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.send('special') }) ``` @@ -134,7 +134,7 @@ function logMethod (req, res, next) { } const logStuff = [logOriginalUrl, logMethod] -app.get('/user/:id', logStuff, function (req, res, next) { +app.get('/user/:id', logStuff, (req, res, next) => { res.send('User Info') }) ``` @@ -156,33 +156,33 @@ const app = express() const router = express.Router() // a middleware function with no mount path. This code is executed for every request to the router -router.use(function (req, res, next) { +router.use((req, res, next) => { console.log('Time:', Date.now()) next() }) // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path -router.use('/user/:id', function (req, res, next) { +router.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) // a middleware sub-stack that handles GET requests to the /user/:id path -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next router if (req.params.id === '0') next('route') // otherwise pass control to the next middleware function in this stack else next() -}, function (req, res, next) { +}, (req, res, next) => { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { console.log(req.params.id) res.render('special') }) @@ -202,17 +202,17 @@ const app = express() const router = express.Router() // predicate the router with a check and bail out when needed -router.use(function (req, res, next) { +router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router') next() }) -router.get('/user/:id', function (req, res) { +router.get('/user/:id', (req, res) => { res.send('hello, user!') }) // use the router and 401 anything falling through -app.use('/admin', router, function (req, res) { +app.use('/admin', router, (req, res) => { res.sendStatus(401) }) ``` @@ -226,7 +226,7 @@ Error-handling middleware always takes _four_ arguments. You must provide four Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`): ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) diff --git a/en/guide/using-template-engines.md b/en/guide/using-template-engines.md index c3255cd325..c7b6ac20b5 100755 --- a/en/guide/using-template-engines.md +++ b/en/guide/using-template-engines.md @@ -64,7 +64,7 @@ Then create a route to render the `index.pug` file. If the `view engine` propert you must specify the extension of the `view` file. Otherwise, you can omit it. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/en/guide/writing-middleware.md b/en/guide/writing-middleware.md index 20890e53bd..1943c13c7d 100755 --- a/en/guide/writing-middleware.md +++ b/en/guide/writing-middleware.md @@ -54,7 +54,7 @@ displays the timestamp of the HTTP request, and one called `validateCookies` tha const express = require('express') const app = express() -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -91,7 +91,7 @@ const myLogger = function (req, res, next) { app.use(myLogger) -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -131,9 +131,9 @@ const requestTime = function (req, res, next) { app.use(requestTime) -app.get('/', function (req, res) { +app.get('/', (req, res) => { let responseText = 'Hello World!
' - responseText += 'Requested at: ' + req.requestTime + '' + responseText += `Requested at: ${req.requestTime}` res.send(responseText) }) @@ -177,7 +177,7 @@ app.use(cookieParser()) app.use(validateCookies) // error handler -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { res.status(400).send(err.message) }) diff --git a/en/starter/basic-routing.md b/en/starter/basic-routing.md index e209499681..84c6aac7f4 100755 --- a/en/starter/basic-routing.md +++ b/en/starter/basic-routing.md @@ -34,7 +34,7 @@ The following examples illustrate defining simple routes. Respond with `Hello World!` on the homepage: ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) ``` @@ -42,7 +42,7 @@ app.get('/', function (req, res) { Respond to POST request on the root route (`/`), the application's home page: ```js -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('Got a POST request') }) ``` @@ -50,7 +50,7 @@ app.post('/', function (req, res) { Respond to a PUT request to the `/user` route: ```js -app.put('/user', function (req, res) { +app.put('/user', (req, res) => { res.send('Got a PUT request at /user') }) ``` @@ -58,7 +58,7 @@ app.put('/user', function (req, res) { Respond to a DELETE request to the `/user` route: ```js -app.delete('/user', function (req, res) { +app.delete('/user', (req, res) => { res.send('Got a DELETE request at /user') }) ``` diff --git a/en/starter/faq.md b/en/starter/faq.md index 91026c86eb..e541ea9946 100755 --- a/en/starter/faq.md +++ b/en/starter/faq.md @@ -61,7 +61,7 @@ do is add a middleware function at the very bottom of the stack (below all other to handle a 404 response: ```js -app.use(function (req, res, next) { +app.use((req, res, next) => { res.status(404).send("Sorry can't find that!") }) ``` @@ -75,7 +75,7 @@ You define error-handling middleware in the same way as other middleware, except with four arguments instead of three; specifically with the signature `(err, req, res, next)`: ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) diff --git a/ja/advanced/developing-template-engines.md b/ja/advanced/developing-template-engines.md index 0eb248b6ea..be87bca993 100755 --- a/ja/advanced/developing-template-engines.md +++ b/ja/advanced/developing-template-engines.md @@ -13,12 +13,12 @@ lang: ja ```js const fs = require('fs') // this engine requires the fs module -app.engine('ntl', function (filePath, options, callback) { // define the template engine - fs.readFile(filePath, function (err, content) { +app.engine('ntl', (filePath, options, callback) => { // define the template engine + fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', '' + options.title + '') - .replace('#message#', '

' + options.message + '

') + const rendered = content.toString().replace('#title#', `${options.title}`) + .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) }) @@ -35,7 +35,7 @@ app.set('view engine', 'ntl') // register the template engine 次に、アプリケーションで次のルートを作成します。 ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/ja/guide/behind-proxies.md b/ja/guide/behind-proxies.md index b46c51936c..e27e62a9e8 100755 --- a/ja/guide/behind-proxies.md +++ b/ja/guide/behind-proxies.md @@ -64,7 +64,7 @@ IP アドレスまたはサブネットは、指定されると、アドレス カスタムの信頼実装。実行内容を理解している場合にのみ、これを使用してください。 ```js -app.set('trust proxy', function (ip) { +app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs else return false }) diff --git a/ja/guide/database-integration.md b/ja/guide/database-integration.md index 2a5d3d1f60..f0954ecfed 100755 --- a/ja/guide/database-integration.md +++ b/ja/guide/database-integration.md @@ -45,7 +45,7 @@ $ npm install cassandra-driver const cassandra = require('cassandra-driver') const client = new cassandra.Client({ contactPoints: ['localhost'] }) -client.execute('select key from system.local', function (err, result) { +client.execute('select key from system.local', (err, result) => { if (err) throw err console.log(result.rows[0]) }) @@ -68,7 +68,7 @@ const couchbase = require('couchbase') const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // add a document to a bucket -bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) { +bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err) } else { @@ -79,7 +79,7 @@ bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, res // get all documents with shoe size 13 const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' const query = N1qlQuery.fromString(n1ql) -bucket.query(query, [13], function (err, result) { +bucket.query(query, [13], (err, result) => { if (err) { console.log(err) } else { @@ -106,7 +106,7 @@ nano.db.create('books') const books = nano.db.use('books') // Insert a book document in the books database -books.insert({ name: 'The Art of war' }, null, function (err, body) { +books.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err) } else { @@ -115,7 +115,7 @@ books.insert({ name: 'The Art of war' }, null, function (err, body) { }) // Get a list of all books -books.list(function (err, body) { +books.list((err, body) => { if (err) { console.log(err) } else { @@ -140,13 +140,13 @@ $ npm install level levelup leveldown const levelup = require('levelup') const db = levelup('./mydb') -db.put('name', 'LevelUP', function (err) { +db.put('name', 'LevelUP', (err) => { if (err) return console.log('Ooops!', err) - db.get('name', function (err, value) { + db.get('name', (err, value) => { if (err) return console.log('Ooops!', err) - console.log('name=' + value) + console.log(`name=${value}`) }) }) ``` @@ -174,7 +174,7 @@ const connection = mysql.createConnection({ connection.connect() -connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => { if (err) throw err console.log('The solution is: ', rows[0].solution) @@ -198,10 +198,10 @@ $ npm install mongodb ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { if (err) throw err - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -214,12 +214,12 @@ MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { if (err) throw err const db = client.db('animals') - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -245,10 +245,10 @@ $ npm install apoc const apoc = require('apoc') apoc.query('match (n) return n').exec().then( - function (response) { + (response) => { console.log(response) }, - function (fail) { + (fail) => { console.log(fail) } ) @@ -317,10 +317,10 @@ const pgp = require('pg-promise')(/* options */) const db = pgp('postgres://username:password@host:port/database') db.one('SELECT $1 AS value', 123) - .then(function (data) { + .then((data) => { console.log('DATA:', data.value) }) - .catch(function (error) { + .catch((error) => { console.log('ERROR:', error) }) ``` @@ -341,19 +341,19 @@ $ npm install redis const redis = require('redis') const client = redis.createClient() -client.on('error', function (err) { - console.log('Error ' + err) +client.on('error', (err) => { + console.log(`Error ${err}`) }) client.set('string key', 'string val', redis.print) client.hset('hash key', 'hashtest 1', 'some value', redis.print) client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) -client.hkeys('hash key', function (err, replies) { - console.log(replies.length + ' replies:') +client.hkeys('hash key', (err, replies) => { + console.log(`${replies.length} replies:`) - replies.forEach(function (reply, i) { - console.log(' ' + i + ': ' + reply) + replies.forEach((reply, i) => { + console.log(` ${i}: ${reply}`) }) client.quit() @@ -384,7 +384,7 @@ const config = { const connection = new Connection(config) -connection.on('connect', function (err) { +connection.on('connect', (err) => { if (err) { console.log(err) } else { @@ -393,17 +393,17 @@ connection.on('connect', function (err) { }) function executeStatement () { - request = new Request("select 123, 'hello world'", function (err, rowCount) { + request = new Request("select 123, 'hello world'", (err, rowCount) => { if (err) { console.log(err) } else { - console.log(rowCount + ' rows') + console.log(`${rowCount} rows`) } connection.close() }) - request.on('row', function (columns) { - columns.forEach(function (column) { + request.on('row', (columns) => { + columns.forEach((column) => { if (column.value === null) { console.log('NULL') } else { @@ -432,18 +432,18 @@ $ npm install sqlite3 const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database(':memory:') -db.serialize(function () { +db.serialize(() => { db.run('CREATE TABLE lorem (info TEXT)') const stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (let i = 0; i < 10; i++) { - stmt.run('Ipsum ' + i) + stmt.run(`Ipsum ${i}`) } stmt.finalize() - db.each('SELECT rowid AS id, info FROM lorem', function (err, row) { - console.log(row.id + ': ' + row.info) + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) }) }) @@ -479,9 +479,9 @@ client.search({ } } } -}).then(function (response) { +}).then((response) => { const hits = response.hits.hits -}, function (error) { +}, (error) => { console.trace(error.message) }) ``` diff --git a/ja/guide/error-handling.md b/ja/guide/error-handling.md index 24132f3d28..9dcd4cd56f 100755 --- a/ja/guide/error-handling.md +++ b/ja/guide/error-handling.md @@ -16,7 +16,7 @@ Expressがルート・ハンドラとミドルウェアの実行中に発生す ルート・ハンドラとミドルウェア内の同期コードで発生するエラーは、余分な作業を必要としません。同期コードがエラーをスローすると、Expressはそれをキャッチして処理します。 例えば: ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { throw new Error('BROKEN') // Express will catch this on its own. }) ``` @@ -24,8 +24,8 @@ app.get('/', function (req, res) { ルート・ハンドラとミドルウェアによって呼び出された非同期関数から返されたエラーについては、それらを`next()`関数に渡す必要があります。ここでExpressはそれらをキャッチして処理します。例えば: ```js -app.get('/', function (req, res, next) { - fs.readFile('/file-does-not-exist', function (err, data) { +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { if (err) { next(err) // Pass errors to Express. } else { @@ -53,8 +53,8 @@ app.get('/', [ ルート・ハンドラまたはミドルウェアによって呼び出された非同期コードで発生したエラーをキャッチして、Expressに渡して処理する必要があります。例えば: ```js -app.get('/', function (req, res, next) { - setTimeout(function () { +app.get('/', (req, res, next) => { + setTimeout(() => { try { throw new Error('BROKEN') } catch (err) { @@ -69,8 +69,8 @@ app.get('/', function (req, res, next) { Promiseを使って`try..catch`ブロックのオーバーヘッドを避けるか、Promiseを返す関数を使うとき。例えば: ```js -app.get('/', function (req, res, next) { - Promise.resolve().then(function () { +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { throw new Error('BROKEN') }).catch(next) // Errors will be passed to Express. }) @@ -83,7 +83,7 @@ Promiseは自動的に同期エラーと拒否されたPromiseをキャッチす ```js app.get('/', [ function (req, res, next) { - fs.readFile('/maybe-valid-file', 'utf8', function (err, data) { + fs.readFile('/maybe-valid-file', 'utf8', (err, data) => { res.locals.data = data next(err) }) @@ -132,7 +132,7 @@ function errorHandler (err, req, res, next) { エラー処理ミドルウェア関数は、その他のミドルウェア関数と同じ方法で定義しますが、エラー処理関数の引数が3つではなく、4つ `(err、req、res、next)` であることが例外です。次に例を示します。 ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) @@ -149,7 +149,7 @@ app.use(bodyParser.urlencoded({ })) app.use(bodyParser.json()) app.use(methodOverride()) -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { // logic }) ``` @@ -210,15 +210,15 @@ function errorHandler (err, req, res, next) { ```js app.get('/a_route_behind_paywall', - function checkIfPaidSubscriber (req, res, next) { + (req, res, next) => { if (!req.user.hasPaid) { // continue handling this request next('route') } else { next() } - }, function getPaidContent (req, res, next) { - PaidContent.find(function (err, doc) { + }, (req, res, next) => { + PaidContent.find((err, doc) => { if (err) return next(err) res.json(doc) }) diff --git a/ja/guide/migrating-4.md b/ja/guide/migrating-4.md index 3e1d9ae99b..89defda126 100755 --- a/ja/guide/migrating-4.md +++ b/ja/guide/migrating-4.md @@ -93,7 +93,7 @@ Express 4 のミドルウェアの完全なリストは、[ここ](https://githu 次に例を示します。 ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) @@ -118,13 +118,13 @@ app.use('/book/:id', function (req, res, next) { ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -142,16 +142,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -325,7 +325,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -442,7 +442,7 @@ if (app.get('env') === 'development') { } var server = http.createServer(app) -server.listen(app.get('port'), function () { +server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -452,7 +452,7 @@ server.listen(app.get('port'), function () { `http` モジュール (socket.io/SPDY/HTTPS) を直接処理する必要がある場合を除き、このモジュールをロードする必要はありません。次のようにして、アプリケーションを簡単に開始できます。 ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -529,7 +529,7 @@ Express アプリケーションの作成またはアプリケーションの開 ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` diff --git a/ja/guide/routing.md b/ja/guide/routing.md index dd6e30b548..3497d2d1bb 100755 --- a/ja/guide/routing.md +++ b/ja/guide/routing.md @@ -26,7 +26,7 @@ const express = require('express') const app = express() // respond with "hello world" when a GET request is made to the homepage -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('hello world') }) ``` @@ -39,12 +39,12 @@ route メソッドは、いずれかの HTTP メソッドから派生され、`e ```js // GET method route -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('GET request to the homepage') }) // POST method route -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('POST request to the homepage') }) ``` @@ -55,7 +55,7 @@ Expressは、すべてのHTTPリクエストメソッドに対応するメソッ _すべての_ HTTPリクエストメソッドのパスにミドルウェア関数をロードするために使用される特別なルーティングメソッド、`app.all()`があります。 たとえば、GET、POST、PUT、DELETE、または[httpモジュール](https://nodejs.org/api/http.html#http_http_methods)でサポートされているその他のHTTPリクエストメソッドを使用するかどうかにかかわらず、"/secret"ルートへのリクエストに対して次のハンドラが実行されます。 ```js -app.all('/secret', function (req, res, next) { +app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') next() // pass control to the next handler }) @@ -82,7 +82,7 @@ Express は、ルート・パスのマッチングに [path-to-regexp](https://w このルート・パスは、リクエストをルートのルート `/` にマッチングします。 ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('root') }) ``` @@ -90,7 +90,7 @@ app.get('/', function (req, res) { このルート・パスは、リクエストを `/about` にマッチングします。 ```js -app.get('/about', function (req, res) { +app.get('/about', (req, res) => { res.send('about') }) ``` @@ -98,7 +98,7 @@ app.get('/about', function (req, res) { このルート・パスは、リクエストを `/random.text` にマッチングします。 ```js -app.get('/random.text', function (req, res) { +app.get('/random.text', (req, res) => { res.send('random.text') }) ``` @@ -108,7 +108,7 @@ app.get('/random.text', function (req, res) { このルート・パスは、`acd` および `abcd` をマッチングします。 ```js -app.get('/ab?cd', function (req, res) { +app.get('/ab?cd', (req, res) => { res.send('ab?cd') }) ``` @@ -116,7 +116,7 @@ app.get('/ab?cd', function (req, res) { このルート・パスは、`abcd`、`abbcd`、`abbbcd` などをマッチングします。 ```js -app.get('/ab+cd', function (req, res) { +app.get('/ab+cd', (req, res) => { res.send('ab+cd') }) ``` @@ -124,7 +124,7 @@ app.get('/ab+cd', function (req, res) { このルート・パスは、`abcd`、`abxcd`、`abRABDOMcd`、`ab123cd` などをマッチングします。 ```js -app.get('/ab*cd', function (req, res) { +app.get('/ab*cd', (req, res) => { res.send('ab*cd') }) ``` @@ -132,7 +132,7 @@ app.get('/ab*cd', function (req, res) { このルート・パスは、`/abe` および `/abcde` をマッチングします。 ```js -app.get('/ab(cd)?e', function (req, res) { +app.get('/ab(cd)?e', (req, res) => { res.send('ab(cd)?e') }) ``` @@ -142,7 +142,7 @@ app.get('/ab(cd)?e', function (req, res) { このルート・パスは、ルート名に「a」が含まれるすべてのものをマッチングします。 ```js -app.get(/a/, function (req, res) { +app.get(/a/, (req, res) => { res.send('/a/') }) ``` @@ -150,7 +150,7 @@ app.get(/a/, function (req, res) { このルート・パスは、`butterfly` および `dragonfly` をマッチングしますが、`butterflyman`、`dragonfly man` などはマッチングしません。 ```js -app.get(/.*fly$/, function (req, res) { +app.get(/.*fly$/, (req, res) => { res.send('/.*fly$/') }) ``` @@ -168,7 +168,7 @@ req.params: { "userId": "34", "bookId": "8989" } ルート・パラメータを使用してルートを定義するには、以下に示すようにルートのパスにルート・パラメータを指定するだけです。 ```js -app.get('/users/:userId/books/:bookId', function (req, res) { +app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params) }) ``` @@ -216,7 +216,7 @@ Express 4.xでは、 単一のコールバック関数で 1 つのルートを処理できます。次に例を示します。 ```js -app.get('/example/a', function (req, res) { +app.get('/example/a', (req, res) => { res.send('Hello from A!') }) ``` @@ -224,10 +224,10 @@ app.get('/example/a', function (req, res) { 複数のコールバック関数で1つのルートを処理できます (必ず、`next` オブジェクトを指定してください)。次に例を示します。 ```js -app.get('/example/b', function (req, res, next) { +app.get('/example/b', (req, res, next) => { console.log('the response will be sent by the next function ...') next() -}, function (req, res) { +}, (req, res) => { res.send('Hello from B!') }) ``` @@ -265,10 +265,10 @@ const cb1 = function (req, res, next) { next() } -app.get('/example/d', [cb0, cb1], function (req, res, next) { +app.get('/example/d', [cb0, cb1], (req, res, next) => { console.log('the response will be sent by the next function ...') next() -}, function (req, res) { +}, (req, res) => { res.send('Hello from D!') }) ``` @@ -298,13 +298,13 @@ app.get('/example/d', [cb0, cb1], function (req, res, next) { ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -322,16 +322,16 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) diff --git a/ja/guide/using-middleware.md b/ja/guide/using-middleware.md index f4994c38ba..98de05450c 100755 --- a/ja/guide/using-middleware.md +++ b/ja/guide/using-middleware.md @@ -40,7 +40,7 @@ Express アプリケーションは、以下のタイプのミドルウェアを ```js const app = express() -app.use(function (req, res, next) { +app.use((req, res, next) => { console.log('Time:', Date.now()) next() }) @@ -49,7 +49,7 @@ app.use(function (req, res, next) { 次の例は、`/user/:id` パスにマウントされたミドルウェア関数を示しています。この関数は、`/user/:id` パスに対するすべてのタイプの HTTP リクエストで実行されます。 ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -58,7 +58,7 @@ app.use('/user/:id', function (req, res, next) { 次の例は、ルートとそのハンドラー関数 (ミドルウェア・システム) を示しています。この関数は、`/user/:id` パスへの GET リクエストを処理します。 ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.send('USER') }) ``` @@ -67,10 +67,10 @@ app.get('/user/:id', function (req, res, next) { `/user/:id` パスへのすべてのタイプの HTTP リクエストに関するリクエスト情報を出力するミドルウェア・サブスタックを示しています。 ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -81,15 +81,15 @@ app.use('/user/:id', function (req, res, next) { 次の例は、`/user/:id` パスへの GET リクエストを処理するミドルウェア・サブスタックを示しています。 ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { console.log('ID:', req.params.id) next() -}, function (req, res, next) { +}, (req, res, next) => { res.send('User Info') }) // handler for the /user/:id path, which prints the user ID -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.end(req.params.id) }) ``` @@ -100,18 +100,18 @@ app.get('/user/:id', function (req, res, next) { 次の例は、`/user/:id` パスへの GET リクエストを処理するミドルウェア・サブスタックを示しています。 ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (Number(req.params.id) === 0) next('route') // otherwise pass the control to the next middleware function in this stack else next() -}, function (req, res, next) { +}, (req, res, next) => { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.render('special') }) ``` @@ -133,33 +133,33 @@ const app = express() const router = express.Router() // a middleware function with no mount path. This code is executed for every request to the router -router.use(function (req, res, next) { +router.use((req, res, next) => { console.log('Time:', Date.now()) next() }) // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path -router.use('/user/:id', function (req, res, next) { +router.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) // a middleware sub-stack that handles GET requests to the /user/:id path -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next router if (Number(req.params.id) === 0) next('route') // otherwise pass control to the next middleware function in this stack else next() -}, function (req, res, next) { +}, (req, res, next) => { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { console.log(req.params.id) res.render('special') }) @@ -177,17 +177,17 @@ const app = express() const router = express.Router() // predicate the router with a check and bail out when needed -router.use(function (req, res, next) { +router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router') next() }) -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('hello, user!') }) // use the router and 401 anything falling through -app.use('/admin', router, function (req, res) { +app.use('/admin', router, (req, res) => { res.sendStatus(401) }) ``` @@ -202,7 +202,7 @@ app.use('/admin', router, function (req, res) { エラー処理ミドルウェア関数は、その他のミドルウェア関数と同じ方法で定義しますが、例外として、シグニチャーで3つではなく4つの引数 `(err、req、res、next)`) を明示的に指定します。 ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) diff --git a/ja/guide/using-template-engines.md b/ja/guide/using-template-engines.md index 83c72ef135..c01c0d82fd 100755 --- a/ja/guide/using-template-engines.md +++ b/ja/guide/using-template-engines.md @@ -56,7 +56,7 @@ html 次に、`index.pug` ファイルをレンダリングするためのルートを作成します。`view engine` プロパティーが設定されていない場合は、`view` ファイルの拡張子を指定する必要があります。そうでない場合は、省略できます。 ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/ja/guide/writing-middleware.md b/ja/guide/writing-middleware.md index c5e34ae89b..896e3ff8e5 100755 --- a/ja/guide/writing-middleware.md +++ b/ja/guide/writing-middleware.md @@ -49,7 +49,7 @@ lang: ja const express = require('express') const app = express() -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -87,7 +87,7 @@ const myLogger = function (req, res, next) { app.use(myLogger) -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -126,9 +126,9 @@ const requestTime = function (req, res, next) { app.use(requestTime) -app.get('/', function (req, res) { +app.get('/', (req, res) => { let responseText = 'Hello World!
' - responseText += 'Requested at: ' + req.requestTime + '' + responseText += `Requested at: ${req.requestTime}` res.send(responseText) }) diff --git a/ko/advanced/developing-template-engines.md b/ko/advanced/developing-template-engines.md index 0d8651a4b0..defbb083b9 100755 --- a/ko/advanced/developing-template-engines.md +++ b/ko/advanced/developing-template-engines.md @@ -13,12 +13,12 @@ lang: ko ```js const fs = require('fs') // this engine requires the fs module -app.engine('ntl', function (filePath, options, callback) { // define the template engine - fs.readFile(filePath, function (err, content) { +app.engine('ntl', (filePath, options, callback) => { // define the template engine + fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', '' + options.title + '') - .replace('#message#', '

' + options.message + '

') + const rendered = content.toString().replace('#title#', `${options.title}`) + .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) }) @@ -35,7 +35,7 @@ app.set('view engine', 'ntl') // register the template engine 이후 앱에 다음과 같은 라우트를 작성하십시오. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/package.json b/package.json index de424686f5..cc95760b7a 100644 --- a/package.json +++ b/package.json @@ -31,25 +31,23 @@ "rules": { "array-callback-return": "off", "no-var": "error", - "node/handle-callback-err": "off" + "node/handle-callback-err": "off", + "object-shorthand": "error", + "prefer-arrow-callback": "error", + "prefer-template": "error" } }, { - "files": "**/3x/*.md/*.js", + "files": [ + "**/3x/*.md/*.js", + "**/4x/*.md/*.js", + "**/guide/migrating-4.md/*.js" + ], "rules": { - "no-var": "off" - } - }, - { - "files": "**/4x/*.md/*.js", - "rules": { - "no-var": "off" - } - }, - { - "files": "**/guide/migrating-4.md/*.js", - "rules": { - "no-var": "off" + "no-var": "off", + "object-shorthand": "off", + "prefer-arrow-callback": "off", + "prefer-template": "off" } } ] diff --git a/th/advanced/developing-template-engines.md b/th/advanced/developing-template-engines.md index e0cfb93c80..75111719e9 100755 --- a/th/advanced/developing-template-engines.md +++ b/th/advanced/developing-template-engines.md @@ -13,12 +13,12 @@ The following code is an example of implementing a very simple template engine f ```js const fs = require('fs') // this engine requires the fs module -app.engine('ntl', function (filePath, options, callback) { // define the template engine - fs.readFile(filePath, function (err, content) { +app.engine('ntl', (filePath, options, callback) => { // define the template engine + fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', '' + options.title + '') - .replace('#message#', '

' + options.message + '

') + const rendered = content.toString().replace('#title#', `${options.title}`) + .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) }) @@ -35,7 +35,7 @@ Your app will now be able to render `.ntl` files. Create a file named `index.ntl Then, create the following route in your app. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/th/guide/behind-proxies.md b/th/guide/behind-proxies.md index 40ef11e8e1..e9abc006b9 100755 --- a/th/guide/behind-proxies.md +++ b/th/guide/behind-proxies.md @@ -56,7 +56,7 @@ Trust the `n`th hop from the front-facing proxy server as the client. Custom trust implementation. Use this only if you know what you are doing. ```js -app.set('trust proxy', function (ip) { +app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs else return false }) diff --git a/th/guide/database-integration.md b/th/guide/database-integration.md index 38eb5fab29..86544475f4 100644 --- a/th/guide/database-integration.md +++ b/th/guide/database-integration.md @@ -43,7 +43,7 @@ $ npm install cassandra-driver const cassandra = require('cassandra-driver') const client = new cassandra.Client({ contactPoints: ['localhost'] }) -client.execute('select key from system.local', function (err, result) { +client.execute('select key from system.local', (err, result) => { if (err) throw err console.log(result.rows[0]) }) @@ -66,7 +66,7 @@ const couchbase = require('couchbase') const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // add a document to a bucket -bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) { +bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err) } else { @@ -77,7 +77,7 @@ bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, res // get all documents with shoe size 13 const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' const query = N1qlQuery.fromString(n1ql) -bucket.query(query, [13], function (err, result) { +bucket.query(query, [13], (err, result) => { if (err) { console.log(err) } else { @@ -104,7 +104,7 @@ nano.db.create('books') const books = nano.db.use('books') // Insert a book document in the books database -books.insert({ name: 'The Art of war' }, null, function (err, body) { +books.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err) } else { @@ -113,7 +113,7 @@ books.insert({ name: 'The Art of war' }, null, function (err, body) { }) // Get a list of all books -books.list(function (err, body) { +books.list((err, body) => { if (err) { console.log(err) } else { @@ -138,13 +138,13 @@ $ npm install level levelup leveldown const levelup = require('levelup') const db = levelup('./mydb') -db.put('name', 'LevelUP', function (err) { +db.put('name', 'LevelUP', (err) => { if (err) return console.log('Ooops!', err) - db.get('name', function (err, value) { + db.get('name', (err, value) => { if (err) return console.log('Ooops!', err) - console.log('name=' + value) + console.log(`name=${value}`) }) }) ``` @@ -172,7 +172,7 @@ const connection = mysql.createConnection({ connection.connect() -connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => { if (err) throw err console.log('The solution is: ', rows[0].solution) @@ -196,10 +196,10 @@ $ npm install mongodb ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { if (err) throw err - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -225,10 +225,10 @@ $ npm install apoc const apoc = require('apoc') apoc.query('match (n) return n').exec().then( - function (response) { + (response) => { console.log(response) }, - function (fail) { + (fail) => { console.log(fail) } ) @@ -297,10 +297,10 @@ const pgp = require('pg-promise')(/* options */) const db = pgp('postgres://username:password@host:port/database') db.one('SELECT $1 AS value', 123) - .then(function (data) { + .then((data) => { console.log('DATA:', data.value) }) - .catch(function (error) { + .catch((error) => { console.log('ERROR:', error) }) ``` @@ -321,19 +321,19 @@ $ npm install redis const redis = require('redis') const client = redis.createClient() -client.on('error', function (err) { - console.log('Error ' + err) +client.on('error', (err) => { + console.log(`Error ${err}`) }) client.set('string key', 'string val', redis.print) client.hset('hash key', 'hashtest 1', 'some value', redis.print) client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) -client.hkeys('hash key', function (err, replies) { - console.log(replies.length + ' replies:') +client.hkeys('hash key', (err, replies) => { + console.log(`${replies.length} replies:`) - replies.forEach(function (reply, i) { - console.log(' ' + i + ': ' + reply) + replies.forEach((reply, i) => { + console.log(` ${i}: ${reply}`) }) client.quit() @@ -364,7 +364,7 @@ const config = { const connection = new Connection(config) -connection.on('connect', function (err) { +connection.on('connect', (err) => { if (err) { console.log(err) } else { @@ -373,17 +373,17 @@ connection.on('connect', function (err) { }) function executeStatement () { - request = new Request("select 123, 'hello world'", function (err, rowCount) { + request = new Request("select 123, 'hello world'", (err, rowCount) => { if (err) { console.log(err) } else { - console.log(rowCount + ' rows') + console.log(`${rowCount} rows`) } connection.close() }) - request.on('row', function (columns) { - columns.forEach(function (column) { + request.on('row', (columns) => { + columns.forEach((column) => { if (column.value === null) { console.log('NULL') } else { @@ -412,18 +412,18 @@ $ npm install sqlite3 const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database(':memory:') -db.serialize(function () { +db.serialize(() => { db.run('CREATE TABLE lorem (info TEXT)') const stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (let i = 0; i < 10; i++) { - stmt.run('Ipsum ' + i) + stmt.run(`Ipsum ${i}`) } stmt.finalize() - db.each('SELECT rowid AS id, info FROM lorem', function (err, row) { - console.log(row.id + ': ' + row.info) + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) }) }) @@ -459,9 +459,9 @@ client.search({ } } } -}).then(function (response) { +}).then((response) => { const hits = response.hits.hits -}, function (error) { +}, (error) => { console.trace(error.message) }) ``` diff --git a/th/guide/error-handling.md b/th/guide/error-handling.md index fa3f418e8a..4b438feec3 100755 --- a/th/guide/error-handling.md +++ b/th/guide/error-handling.md @@ -11,7 +11,7 @@ except error-handling functions have four arguments instead of three: `(err, req, res, next)`. For example: ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) @@ -28,7 +28,7 @@ app.use(bodyParser.urlencoded({ })) app.use(bodyParser.json()) app.use(methodOverride()) -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { // logic }) ``` @@ -93,15 +93,15 @@ If you have a route handler with multiple callback functions you can use the `ro ```js app.get('/a_route_behind_paywall', - function checkIfPaidSubscriber (req, res, next) { + (req, res, next) => { if (!req.user.hasPaid) { // continue handling this request next('route') } else { next() } - }, function getPaidContent (req, res, next) { - PaidContent.find(function (err, doc) { + }, (req, res, next) => { + PaidContent.find((err, doc) => { if (err) return next(err) res.json(doc) }) diff --git a/th/guide/migrating-4.md b/th/guide/migrating-4.md index d700f818c5..795c4bd136 100755 --- a/th/guide/migrating-4.md +++ b/th/guide/migrating-4.md @@ -99,7 +99,7 @@ In version 4 you can use a variable parameter to define the path where middlewar For example: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) @@ -129,13 +129,13 @@ Here is an example of chained route handlers that are defined by using the `app. ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -158,16 +158,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -349,7 +349,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -477,7 +477,7 @@ if (app.get('env') === 'development') { } var server = http.createServer(app) -server.listen(app.get('port'), function () { +server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -486,7 +486,7 @@ server.listen(app.get('port'), function () { Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -587,7 +587,7 @@ delete the line that says `module.exports = app;` at the end of the ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` diff --git a/th/guide/routing.md b/th/guide/routing.md index 782c8213ea..0567bdaee4 100755 --- a/th/guide/routing.md +++ b/th/guide/routing.md @@ -28,7 +28,7 @@ const express = require('express') const app = express() // respond with "hello world" when a GET request is made to the homepage -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('hello world') }) ``` @@ -41,12 +41,12 @@ The following code is an example of routes that are defined for the GET and the ```js // GET method route -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('GET request to the homepage') }) // POST method route -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('POST request to the homepage') }) ``` @@ -57,7 +57,7 @@ or a full list, see [app.METHOD](/{{ page.lang }}/4x/api.html#app.METHOD). There is a special routing method, `app.all()`, used to load middleware functions at a path for _all_ HTTP request methods. For example, the following handler is executed for requests to the route "/secret" whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the [http module](https://nodejs.org/api/http.html#http_http_methods). ```js -app.all('/secret', function (req, res, next) { +app.all('/secret', (req, res, next) => { console.log('Accessing the secret section ...') next() // pass control to the next handler }) @@ -84,7 +84,7 @@ Here are some examples of route paths based on strings. This route path will match requests to the root route, `/`. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('root') }) ``` @@ -92,7 +92,7 @@ app.get('/', function (req, res) { This route path will match requests to `/about`. ```js -app.get('/about', function (req, res) { +app.get('/about', (req, res) => { res.send('about') }) ``` @@ -100,7 +100,7 @@ app.get('/about', function (req, res) { This route path will match requests to `/random.text`. ```js -app.get('/random.text', function (req, res) { +app.get('/random.text', (req, res) => { res.send('random.text') }) ``` @@ -110,7 +110,7 @@ Here are some examples of route paths based on string patterns. This route path will match `acd` and `abcd`. ```js -app.get('/ab?cd', function (req, res) { +app.get('/ab?cd', (req, res) => { res.send('ab?cd') }) ``` @@ -118,7 +118,7 @@ app.get('/ab?cd', function (req, res) { This route path will match `abcd`, `abbcd`, `abbbcd`, and so on. ```js -app.get('/ab+cd', function (req, res) { +app.get('/ab+cd', (req, res) => { res.send('ab+cd') }) ``` @@ -126,7 +126,7 @@ app.get('/ab+cd', function (req, res) { This route path will match `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd`, and so on. ```js -app.get('/ab*cd', function (req, res) { +app.get('/ab*cd', (req, res) => { res.send('ab*cd') }) ``` @@ -134,7 +134,7 @@ app.get('/ab*cd', function (req, res) { This route path will match `/abe` and `/abcde`. ```js -app.get('/ab(cd)?e', function (req, res) { +app.get('/ab(cd)?e', (req, res) => { res.send('ab(cd)?e') }) ``` @@ -144,7 +144,7 @@ Examples of route paths based on regular expressions: This route path will match anything with an "a" in the route name. ```js -app.get(/a/, function (req, res) { +app.get(/a/, (req, res) => { res.send('/a/') }) ``` @@ -152,7 +152,7 @@ app.get(/a/, function (req, res) { This route path will match `butterfly` and `dragonfly`, but not `butterflyman`, `dragonflyman`, and so on. ```js -app.get(/.*fly$/, function (req, res) { +app.get(/.*fly$/, (req, res) => { res.send('/.*fly$/') }) ``` @@ -170,7 +170,7 @@ req.params: { "userId": "34", "bookId": "8989" } To define routes with route parameters, simply specify the route parameters in the path of the route as shown below. ```js -app.get('/users/:userId/books/:bookId', function (req, res) { +app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params) }) ``` @@ -218,7 +218,7 @@ Route handlers can be in the form of a function, an array of functions, or combi A single callback function can handle a route. For example: ```js -app.get('/example/a', function (req, res) { +app.get('/example/a', (req, res) => { res.send('Hello from A!') }) ``` @@ -226,10 +226,10 @@ app.get('/example/a', function (req, res) { More than one callback function can handle a route (make sure you specify the `next` object). For example: ```js -app.get('/example/b', function (req, res, next) { +app.get('/example/b', (req, res, next) => { console.log('the response will be sent by the next function ...') next() -}, function (req, res) { +}, (req, res) => { res.send('Hello from B!') }) ``` @@ -267,10 +267,10 @@ const cb1 = function (req, res, next) { next() } -app.get('/example/d', [cb0, cb1], function (req, res, next) { +app.get('/example/d', [cb0, cb1], (req, res, next) => { console.log('the response will be sent by the next function ...') next() -}, function (req, res) { +}, (req, res) => { res.send('Hello from D!') }) ``` @@ -300,13 +300,13 @@ Here is an example of chained route handlers that are defined by using `app.rout ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -324,16 +324,16 @@ const express = require('express') const router = express.Router() // middleware that is specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) diff --git a/th/guide/using-middleware.md b/th/guide/using-middleware.md index c34eff82a2..95139da24a 100644 --- a/th/guide/using-middleware.md +++ b/th/guide/using-middleware.md @@ -39,7 +39,7 @@ This example shows a middleware function with no mount path. The function is exe ```js const app = express() -app.use(function (req, res, next) { +app.use((req, res, next) => { console.log('Time:', Date.now()) next() }) @@ -49,7 +49,7 @@ This example shows a middleware function mounted on the `/user/:id` path. The fu HTTP request on the `/user/:id` path. ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -58,7 +58,7 @@ app.use('/user/:id', function (req, res, next) { This example shows a route and its handler function (middleware system). The function handles GET requests to the `/user/:id` path. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.send('USER') }) ``` @@ -67,10 +67,10 @@ Here is an example of loading a series of middleware functions at a mount point, It illustrates a middleware sub-stack that prints request info for any type of HTTP request to the `/user/:id` path. ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -81,15 +81,15 @@ Route handlers enable you to define multiple routes for a path. The example belo This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { console.log('ID:', req.params.id) next() -}, function (req, res, next) { +}, (req, res, next) => { res.send('User Info') }) // handler for the /user/:id path, which prints the user ID -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.end(req.params.id) }) ``` @@ -100,18 +100,18 @@ To skip the rest of the middleware functions from a router middleware stack, cal This example shows a middleware sub-stack that handles GET requests to the `/user/:id` path. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next route if (req.params.id === '0') next('route') // otherwise pass the control to the next middleware function in this stack else next() -}, function (req, res, next) { +}, (req, res, next) => { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.render('special') }) ``` @@ -132,33 +132,33 @@ const app = express() const router = express.Router() // a middleware function with no mount path. This code is executed for every request to the router -router.use(function (req, res, next) { +router.use((req, res, next) => { console.log('Time:', Date.now()) next() }) // a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path -router.use('/user/:id', function (req, res, next) { +router.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) // a middleware sub-stack that handles GET requests to the /user/:id path -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { // if the user ID is 0, skip to the next router if (req.params.id === '0') next('route') // otherwise pass control to the next middleware function in this stack else next() -}, function (req, res, next) { +}, (req, res, next) => { // render a regular page res.render('regular') }) // handler for the /user/:id path, which renders a special page -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { console.log(req.params.id) res.render('special') }) @@ -177,17 +177,17 @@ const app = express() const router = express.Router() // predicate the router with a check and bail out when needed -router.use(function (req, res, next) { +router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router') next() }) -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('hello, user!') }) // use the router and 401 anything falling through -app.use('/admin', router, function (req, res) { +app.use('/admin', router, (req, res) => { res.sendStatus(401) }) ``` @@ -201,7 +201,7 @@ Error-handling middleware always takes _four_ arguments. You must provide four Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`): ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) diff --git a/th/guide/using-template-engines.md b/th/guide/using-template-engines.md index e795c29f64..5cab6fc578 100755 --- a/th/guide/using-template-engines.md +++ b/th/guide/using-template-engines.md @@ -63,7 +63,7 @@ Then create a route to render the `index.pug` file. If the `view engine` propert you must specify the extension of the `view` file. Otherwise, you can omit it. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/th/guide/writing-middleware.md b/th/guide/writing-middleware.md index 006322faee..18dfd26889 100755 --- a/th/guide/writing-middleware.md +++ b/th/guide/writing-middleware.md @@ -51,7 +51,7 @@ displays the timestamp of the HTTP request. const express = require('express') const app = express() -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -88,7 +88,7 @@ const myLogger = function (req, res, next) { app.use(myLogger) -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -128,9 +128,9 @@ const requestTime = function (req, res, next) { app.use(requestTime) -app.get('/', function (req, res) { +app.get('/', (req, res) => { let responseText = 'Hello World!
' - responseText += 'Requested at: ' + req.requestTime + '' + responseText += `Requested at: ${req.requestTime}` res.send(responseText) }) diff --git a/th/starter/basic-routing.md b/th/starter/basic-routing.md index 59b12c1bef..6dbc4ff5e8 100755 --- a/th/starter/basic-routing.md +++ b/th/starter/basic-routing.md @@ -33,7 +33,7 @@ app.METHOD(PATH, HANDLER) ตอบสนองด้วยข้อความ `Hello World!` บนเพจหลัก: ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) ``` @@ -41,7 +41,7 @@ app.get('/', function (req, res) { ตอบสนองต่อการร้องขอด้วยวิธี POST บนเส้นทาง root (`/`) บนเพจหลักของแอปพลิเคชัน: ```js -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('Got a POST request') }) ``` @@ -49,7 +49,7 @@ app.post('/', function (req, res) { ตอบสนองต่อการร้องขอด้วยวิธี PUT บนเส้นทาง `/user`: ```js -app.put('/user', function (req, res) { +app.put('/user', (req, res) => { res.send('Got a PUT request at /user') }) ``` @@ -57,7 +57,7 @@ app.put('/user', function (req, res) { ตอบสนองต่อการร้องขอด้วยวิธี DELETE บนเส้นทาง `/user`: ```js -app.delete('/user', function (req, res) { +app.delete('/user', (req, res) => { res.send('Got a DELETE request at /user') }) ``` diff --git a/th/starter/faq.md b/th/starter/faq.md index 218ecebd70..2c11c36938 100755 --- a/th/starter/faq.md +++ b/th/starter/faq.md @@ -52,7 +52,7 @@ Express รองรับทุก template engine ที่สอดคล้ สิ่งที่คุณต้องทำคือเพิ่มฟังก์ชันมิดเดิลแวร์ที่ด้านล่างสุดเพื่อจัดการกับการตอบสนอง 404: ```js -app.use(function (req, res, next) { +app.use((req, res, next) => { res.status(404).send("Sorry can't find that!") }) ``` @@ -63,7 +63,7 @@ app.use(function (req, res, next) { ดังนี้ `(err, req, res, next)` ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Something broke!') }) diff --git a/tr/advanced/developing-template-engines.md b/tr/advanced/developing-template-engines.md index d58216e1f9..c01cbcc1ec 100644 --- a/tr/advanced/developing-template-engines.md +++ b/tr/advanced/developing-template-engines.md @@ -13,12 +13,12 @@ The following code is an example of implementing a very simple template engine f ```js const fs = require('fs') // this engine requires the fs module -app.engine('ntl', function (filePath, options, callback) { // define the template engine - fs.readFile(filePath, function (err, content) { +app.engine('ntl', (filePath, options, callback) => { // define the template engine + fs.readFile(filePath, (err, content) => { if (err) return callback(err) // this is an extremely simple template engine - const rendered = content.toString().replace('#title#', '' + options.title + '') - .replace('#message#', '

' + options.message + '

') + const rendered = content.toString().replace('#title#', `${options.title}`) + .replace('#message#', `

${options.message}

`) return callback(null, rendered) }) }) @@ -35,7 +35,7 @@ Your app will now be able to render `.ntl` files. Create a file named `index.ntl Then, create the following route in your app. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/tr/guide/behind-proxies.md b/tr/guide/behind-proxies.md index bdf352dc5f..774c102a27 100644 --- a/tr/guide/behind-proxies.md +++ b/tr/guide/behind-proxies.md @@ -59,7 +59,7 @@ Belirtildiğinde, IP adresleri veya alt ağlar adres belirleme işleminin dış ```js -app.set('trust proxy', function (ip) { +app.set('trust proxy', (ip) => { if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // güvenilen IP'ler else return false }) diff --git a/tr/guide/database-integration.md b/tr/guide/database-integration.md index b10debbe33..db321a951e 100644 --- a/tr/guide/database-integration.md +++ b/tr/guide/database-integration.md @@ -43,7 +43,7 @@ $ npm install cassandra-driver const cassandra = require('cassandra-driver') const client = new cassandra.Client({ contactPoints: ['localhost'] }) -client.execute('select key from system.local', function (err, result) { +client.execute('select key from system.local', (err, result) => { if (err) throw err console.log(result.rows[0]) }) @@ -66,7 +66,7 @@ const couchbase = require('couchbase') const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // bir dökümanı bir kovaya ekle -bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) { +bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err) } else { @@ -77,7 +77,7 @@ bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, res // "shoe" alanının değeri 13 olan bütün dökümanları getir const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' const query = N1qlQuery.fromString(n1ql) -bucket.query(query, [13], function (err, result) { +bucket.query(query, [13], (err, result) => { if (err) { console.log(err) } else { @@ -104,7 +104,7 @@ nano.db.create('books') const books = nano.db.use('books') // books veritabanına bir kitap ekle -books.insert({ name: 'The Art of war' }, null, function (err, body) { +books.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err) } else { @@ -113,7 +113,7 @@ books.insert({ name: 'The Art of war' }, null, function (err, body) { }) // bütün kitapların bir listesini getir -books.list(function (err, body) { +books.list((err, body) => { if (err) { console.log(err) } else { @@ -138,13 +138,13 @@ $ npm install level levelup leveldown const levelup = require('levelup') const db = levelup('./mydb') -db.put('name', 'LevelUP', function (err) { +db.put('name', 'LevelUP', (err) => { if (err) return console.log('Ooops!', err) - db.get('name', function (err, value) { + db.get('name', (err, value) => { if (err) return console.log('Ooops!', err) - console.log('name=' + value) + console.log(`name=${value}`) }) }) ``` @@ -172,7 +172,7 @@ const connection = mysql.createConnection({ connection.connect() -connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => { if (err) throw err console.log('The solution is: ', rows[0].solution) @@ -196,10 +196,10 @@ $ npm install mongodb ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { if (err) throw err - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -212,12 +212,12 @@ MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { if (err) throw err const db = client.db('animals') - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -243,10 +243,10 @@ $ npm install apoc const apoc = require('apoc') apoc.query('match (n) return n').exec().then( - function (response) { + (response) => { console.log(response) }, - function (fail) { + (fail) => { console.log(fail) } ) @@ -315,10 +315,10 @@ const pgp = require('pg-promise')(/* seçenekler */) const db = pgp('postgres://username:password@host:port/database') db.one('SELECT $1 AS value', 123) - .then(function (data) { + .then((data) => { console.log('DATA:', data.value) }) - .catch(function (error) { + .catch((error) => { console.log('ERROR:', error) }) ``` @@ -339,19 +339,19 @@ $ npm install redis const redis = require('redis') const client = redis.createClient() -client.on('error', function (err) { - console.log('Error ' + err) +client.on('error', (err) => { + console.log(`Error ${err}`) }) client.set('string key', 'string val', redis.print) client.hset('hash key', 'hashtest 1', 'some value', redis.print) client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) -client.hkeys('hash key', function (err, replies) { - console.log(replies.length + ' replies:') +client.hkeys('hash key', (err, replies) => { + console.log(`${replies.length} replies:`) - replies.forEach(function (reply, i) { - console.log(' ' + i + ': ' + reply) + replies.forEach((reply, i) => { + console.log(` ${i}: ${reply}`) }) client.quit() @@ -387,7 +387,7 @@ const config = { const connection = new Connection(config) -connection.on('connect', function (err) { +connection.on('connect', (err) => { if (err) { console.log(err) } else { @@ -396,17 +396,17 @@ connection.on('connect', function (err) { }) function executeStatement () { - request = new Request("select 123, 'hello world'", function (err, rowCount) { + request = new Request("select 123, 'hello world'", (err, rowCount) => { if (err) { console.log(err) } else { - console.log(rowCount + ' rows') + console.log(`${rowCount} rows`) } connection.close() }) - request.on('row', function (columns) { - columns.forEach(function (column) { + request.on('row', (columns) => { + columns.forEach((column) => { if (column.value === null) { console.log('NULL') } else { @@ -435,18 +435,18 @@ $ npm install sqlite3 const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database(':memory:') -db.serialize(function () { +db.serialize(() => { db.run('CREATE TABLE lorem (info TEXT)') const stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (let i = 0; i < 10; i++) { - stmt.run('Ipsum ' + i) + stmt.run(`Ipsum ${i}`) } stmt.finalize() - db.each('SELECT rowid AS id, info FROM lorem', function (err, row) { - console.log(row.id + ': ' + row.info) + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) }) }) @@ -482,9 +482,9 @@ client.search({ } } } -}).then(function (response) { +}).then((response) => { const hits = response.hits.hits -}, function (error) { +}, (error) => { console.trace(error.message) }) ``` \ No newline at end of file diff --git a/tr/guide/error-handling.md b/tr/guide/error-handling.md index d9538386ad..3b1033b04c 100644 --- a/tr/guide/error-handling.md +++ b/tr/guide/error-handling.md @@ -15,7 +15,7 @@ Express tarafından, rota işleyicileri ve ara yazılımları koşarken oluşan Rota işleyicilerinde ve ara yazılımlarda senkron kodda oluşan hataları yakalamak için ek birşey yapmaka gerek yoktur. Eğer senkron kod bir hata fırlatırsa, Express onu yakalayıp işleyecektir. Örneğin: ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { throw new Error('BROKEN') // Express bunu kendi kendine yakalayacak }) ``` @@ -23,8 +23,8 @@ app.get('/', function (req, res) { Rota işleyicileri ve ara yazılım tarafından çağrılan asenkron fonksiyonlardan dönen hataları Express'in yakalayp işleyeceği `next()` fonksiyonuna vermelisiniz. Örnek olarak: ```js -app.get('/', function (req, res, next) { - fs.readFile('/file-does-not-exist', function (err, data) { +app.get('/', (req, res, next) => { + fs.readFile('/file-does-not-exist', (err, data) => { if (err) { next(err) // Hataları Express'e ver } else { @@ -37,7 +37,7 @@ app.get('/', function (req, res, next) { Express 5 ile başlayarak, Promise döndüren rota işleyicileri ve ara yazılımlar ret verdiklerinde (reject) veya hata fırlattıklarında otomatik olarak `next(value)` fonksiyonunu çağıracaklar. Örneğin: ```js -app.get('/user/:id', async function (req, res, next) { +app.get('/user/:id', async (req, res, next) => { const user = await getUserById(req.params.id) res.send(user) }) @@ -65,8 +65,8 @@ Yukarıdaki örnekte `next`, hata veya hatasız olarak çağrılan `fs.writeFile Rota işleyicileri ve ara yazılımlar tarafından çağrılan asenkron kodda oluşan hataları yakalayıp işlemesi için Express'e geçmelisiniz. Örnek olarak: ```js -app.get('/', function (req, res, next) { - setTimeout(function () { +app.get('/', (req, res, next) => { + setTimeout(() => { try { throw new Error('BROKEN') } catch (err) { @@ -81,8 +81,8 @@ Yukarıdaki örnek asenkron kodda hataları yakalamak için bir `try...catch` bl `try..catch` blokunun yükünden kaçınmak için promise veya promise döndüren fonksiyonlar kullanın. Örnek olarak: ```js -app.get('/', function (req, res, next) { - Promise.resolve().then(function () { +app.get('/', (req, res, next) => { + Promise.resolve().then(() => { throw new Error('BROKEN') }).catch(next) // Hatalar Express'e geçer }) @@ -96,7 +96,7 @@ Senkron hata yakalamaya güvenmek için asenkron kodu basite indirgeyerek bir i ```js app.get('/', [ function (req, res, next) { - fs.readFile('/maybe-valid-file', 'utf-8', function (err, data) { + fs.readFile('/maybe-valid-file', 'utf-8', (err, data) => { res.locals.data = data next(err) }) @@ -150,7 +150,7 @@ Kodunuzda `next()` fonksiyonunu bir hata ile birden fazla kez çağırdığını Hata işleyici ara yazılım fonksiyonlarını diğer ara yazılım fonksiyonları gibi tanımlayınız, bundan farklı olarak hata işleyici fonksiyonlar üç yerine dört argümana sahipler: `(err, req, res, next)`. Örneğin: ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Birşeyler bozuldu') }) @@ -167,7 +167,7 @@ app.use(bodyParser.urlencoded({ })) app.use(bodyParser.json()) app.use(methodOverride()) -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { // iş mantığı }) ``` @@ -226,15 +226,15 @@ Birden fazla geri çağırma fonksiyonu olan bir rota işleyiciniz var ise bir s ```js app.get('/a_route_behind_paywall', - function checkIfPaidSubscriber (req, res, next) { + (req, res, next) => { if (!req.user.hasPaid) { // bu isteği işlemeye devam et next('route') } else { next() } - }, function getPaidContent (req, res, next) { - PaidContent.find(function (err, doc) { + }, (req, res, next) => { + PaidContent.find((err, doc) => { if (err) return next(err) res.json(doc) }) diff --git a/tr/guide/migrating-4.md b/tr/guide/migrating-4.md index cb3a494951..d253cf37d5 100644 --- a/tr/guide/migrating-4.md +++ b/tr/guide/migrating-4.md @@ -100,7 +100,7 @@ In version 4 you can use a variable parameter to define the path where middlewar For example: ```js -app.use('/book/:id', function (req, res, next) { +app.use('/book/:id', (req, res, next) => { console.log('ID:', req.params.id) next() }) @@ -130,13 +130,13 @@ Here is an example of chained route handlers that are defined by using the `app. ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Get a random book') }) - .post(function (req, res) { + .post((req, res) => { res.send('Add a book') }) - .put(function (req, res) { + .put((req, res) => { res.send('Update the book') }) ``` @@ -159,16 +159,16 @@ var express = require('express') var router = express.Router() // middleware specific to this router -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // define the home page route -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) @@ -350,7 +350,7 @@ if (app.get('env') === 'development') { app.get('/', routes.index) app.get('/users', user.list) -http.createServer(app).listen(app.get('port'), function () { +http.createServer(app).listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -478,7 +478,7 @@ if (app.get('env') === 'development') { } var server = http.createServer(app) -server.listen(app.get('port'), function () { +server.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -487,7 +487,7 @@ server.listen(app.get('port'), function () { Unless you need to work directly with the `http` module (socket.io/SPDY/HTTPS), loading it is not required, and the app can be simply started this way: ```js -app.listen(app.get('port'), function () { +app.listen(app.get('port'), () => { console.log('Express server listening on port ' + app.get('port')) }) ``` @@ -588,7 +588,7 @@ delete the line that says `module.exports = app;` at the end of the ```js app.set('port', process.env.PORT || 3000) -var server = app.listen(app.get('port'), function () { +var server = app.listen(app.get('port'), () => { debug('Express server listening on port ' + server.address().port) }) ``` diff --git a/tr/guide/overriding-express-api.md b/tr/guide/overriding-express-api.md index 1ad1c2b18f..cfa1a02bf1 100644 --- a/tr/guide/overriding-express-api.md +++ b/tr/guide/overriding-express-api.md @@ -55,7 +55,7 @@ Aşağıdaki kod `req.ip` alanının değerinin nasıl türetileceğini yeniden Object.defineProperty(app.request, 'ip', { configurable: true, enumerable: true, - get: function () { return this.get('Client-IP') } + get () { return this.get('Client-IP') } }) ``` diff --git a/tr/guide/routing.md b/tr/guide/routing.md index e6aab24c88..f7b140cc31 100644 --- a/tr/guide/routing.md +++ b/tr/guide/routing.md @@ -23,7 +23,7 @@ const express = require('express') const app = express() // anasayfaya bir GET isteği yapıldığında "merhaba dünya" ile yanıt verir -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('merhaba dünya') }) ``` @@ -36,12 +36,12 @@ Aşağıdaki kod uygulamanın köküne GET ve POST metodları için tanımlanan ```js // GET metodu rotası -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('anasayfaya GET isteği') }) // POST metodu rotası -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('anasayfaya POST isteği') }) ``` @@ -58,7 +58,7 @@ Hiçbir HTTP metodundan türemeyen özel bir yönlendirme metodu olan `app.all() Bir sonraki örnekte, "/secret" rotasına yapılan isteklerde, GET, POST, PUT, DELETE veya [http modülü](https://nodejs.org/api/http.html#http_http_methods)'nde desteklenen herhangi bir HTTP istek metodu farketmeksizin bu işleyici çalıştırılacak. ```js -app.all('/secret', function (req, res, next) { +app.all('/secret', (req, res, next) => { console.log('Gizli bölümlere erişiliyor...') next() // bir sonraki işleyiciye kontrolü verir }) @@ -85,7 +85,7 @@ Karakter dizininlerine dayalı bazı rota yolları örnekleri. Bu rota yolu, istekleri kök rotaya eşleştirecek, `/`. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('root') }) ``` @@ -93,7 +93,7 @@ app.get('/', function (req, res) { Bu rota yolu istekleri `/about` ile eşleştirecek ```js -app.get('/about', function (req, res) { +app.get('/about', (req, res) => { res.send('about') }) ``` @@ -101,7 +101,7 @@ app.get('/about', function (req, res) { Bu rota yolu istekleri `/random.text` ile eşleştirecek ```js -app.get('/random.text', function (req, res) { +app.get('/random.text', (req, res) => { res.send('random.text') }) ``` @@ -111,7 +111,7 @@ Aşağıda, dizin modellerine dayalı rota yollarının bazı örnekleri verilmi Bu rota yolu, `acd` ve `abcd` ile eşleşecek. ```js -app.get('/ab?cd', function (req, res) { +app.get('/ab?cd', (req, res) => { res.send('ab?cd') }) ``` @@ -119,7 +119,7 @@ app.get('/ab?cd', function (req, res) { Bu rota yolu, `abcd`, `abbcd`, `abbbcd` vb. ile eşleşecek. ```js -app.get('/ab+cd', function (req, res) { +app.get('/ab+cd', (req, res) => { res.send('ab+cd') }) ``` @@ -127,7 +127,7 @@ app.get('/ab+cd', function (req, res) { Bu rota yolu, `abcd`, `abxcd`, `abRANDOMcd`, `ab123cd` vb. ile eşleşecek. ```js -app.get('/ab*cd', function (req, res) { +app.get('/ab*cd', (req, res) => { res.send('ab*cd') }) ``` @@ -135,7 +135,7 @@ app.get('/ab*cd', function (req, res) { Bu rota yolu, `/abe` ve `/abcde` ile eşleşecek. ```js -app.get('/ab(cd)?e', function (req, res) { +app.get('/ab(cd)?e', (req, res) => { res.send('ab(cd)?e') }) ``` @@ -145,7 +145,7 @@ Düzenli ifadelere dayalı rota yolları örnekleri: Bu rota yolu, rota isminde "a" karakteri olan herhangi bir şey ile eşleşecek. ```js -app.get(/a/, function (req, res) { +app.get(/a/, (req, res) => { res.send('/a/') }) ``` @@ -153,7 +153,7 @@ app.get(/a/, function (req, res) { Bu rota yolu `butterfly` ve `dragonfly` ile eşleşir, ancak `butterflyman`, `dragonflyman` vb. ile değil. ```js -app.get(/.*fly$/, function (req, res) { +app.get(/.*fly$/, (req, res) => { res.send('/.*fly$/') }) ``` @@ -171,7 +171,7 @@ req.params: { "userId": "34", "bookId": "8989" } Parametreli rota tanımlamak için, aşağıda gösterildiği gibi rota parametrelerini rotanın yolunda belirtmeniz yeterlidir. ```js -app.get('/users/:userId/books/:bookId', function (req, res) { +app.get('/users/:userId/books/:bookId', (req, res) => { res.send(req.params) }) ``` @@ -220,7 +220,7 @@ Rota işleyicileri, aşağıdaki örneklerde gösterildiği gibi bir fonksiyon, Bir geri çağırma fonksiyonu, bir rotayı işleyebilir. Örneğin: ```js -app.get('/example/a', function (req, res) { +app.get('/example/a', (req, res) => { res.send('A\'dan merhaba') }) ``` @@ -228,10 +228,10 @@ app.get('/example/a', function (req, res) { Birden fazla geri çağırma fonksiyonu bir rotayı işleyebilir (`next` objesini belirttiğinizden emin olun). Örneğin: ```js -app.get('/example/b', function (req, res, next) { +app.get('/example/b', (req, res, next) => { console.log('yanıt bir sonraki fonksiyon tarafından gönderilecek') next() -}, function (req, res) { +}, (req, res) => { res.send('B\'den merhaba') }) ``` @@ -268,10 +268,10 @@ const cb1 = function (req, res, next) { next() } -app.get('/example/d', [cb0, cb1], function (req, res, next) { +app.get('/example/d', [cb0, cb1], (req, res, next) => { console.log('yanıt bir sonraki fonksiyon tarafından gönderilecek') next() -}, function (req, res) { +}, (req, res) => { res.send('D\'den merhaba') }) ``` @@ -301,13 +301,13 @@ Burada `app.route()` kullanılarak tanımlanan zincirleme rota işleyicilerine b ```js app.route('/book') - .get(function (req, res) { + .get((req, res) => { res.send('Rastgele bir kitap getir') }) - .post(function (req, res) { + .post((req, res) => { res.send('Bir kitap ekle') }) - .put(function (req, res) { + .put((req, res) => { res.send('Kitabı güncelle') }) ``` @@ -325,16 +325,16 @@ const express = require('express') const router = express.Router() // bu yönlendiriciye özel ara katman yazılım -router.use(function timeLog (req, res, next) { +router.use((req, res, next) => { console.log('Time: ', Date.now()) next() }) // anasayfa rotası tanımla -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('Birds home page') }) // define the about route -router.get('/about', function (req, res) { +router.get('/about', (req, res) => { res.send('About birds') }) diff --git a/tr/guide/using-middleware.md b/tr/guide/using-middleware.md index f93720ee3f..2df297142b 100644 --- a/tr/guide/using-middleware.md +++ b/tr/guide/using-middleware.md @@ -41,7 +41,7 @@ Bu örnek, hedef yolu bulunmayan bir ara yazılım fonksiyonunu gösteriyor. Fon ```js const app = express() -app.use(function (req, res, next) { +app.use((req, res, next) => { console.log('Time:', Date.now()) next() }) @@ -50,7 +50,7 @@ app.use(function (req, res, next) { Bu örnek, `/user/:id` yoluna yerleştirilmiş bir ara yazılım fonksiyonu gösterir. Bu fonksiyon `/user/:id` yoluna yapılan herhangi bir HTTP isteğinde çalışır. ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -59,7 +59,7 @@ app.use('/user/:id', function (req, res, next) { Bu örnek bir rotayı ve işleyici fonksiyonunu gösterir (ara yazılım sistemi). Fonksiyon `/user/:id` yoluna yapılan GET isteklerini karşılıyor. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.send('USER') }) ``` @@ -68,10 +68,10 @@ Bu örnek, hedef bir yol ile, yerleştirilmiş bir noktada bir dizi ara yazılı `/user/:id` yoluna yapılan herhangi bir tipte HTTP isteğinin istek bilgilerini yazdıran bir ara yazılım alt kümesini gösterir. ```js -app.use('/user/:id', function (req, res, next) { +app.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) @@ -82,15 +82,15 @@ Rota işleyicileri bir yol için birden fazla rota tanımlamaya olanak sağlar. Bu örnek `/user/:id` yoluna yapılan GET isteklerini işleyen ara yazılım alt kümesini gösterir. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { console.log('ID:', req.params.id) next() -}, function (req, res, next) { +}, (req, res, next) => { res.send('User Info') }) // kullanıcı ID'sini yazdıran, /user/:id yolunun işleyicisi -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.end(req.params.id) }) ``` @@ -101,18 +101,18 @@ Geriye kalan ara yazılım fonksiyonlarını yönlendirici ara yazılım kümesi Bu örnek `/user/:id` yolu için yapılan GET isteklerini işleyen bir ara yazılım alt-kümesini gösterir. ```js -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { // kullanıcı ID'si 0 ise, bir sonraki rotaya geç if (req.params.id === '0') next('route') // aksi takdirde kontrolü bu kümedeki bir sonraki ara yazılım fonksiyonuna ver else next() -}, function (req, res, next) { +}, (req, res, next) => { // normal bir sayfa göster res.render('regular') }) // özel bir sayfa gösteren, /user/:id yolunun işleyicisi -app.get('/user/:id', function (req, res, next) { +app.get('/user/:id', (req, res, next) => { res.render('special') }) ``` @@ -133,33 +133,33 @@ const app = express() const router = express.Router() // hedef yolu olmayan bir ara yazılım fonksiyonu. Bu kod yönlendiriciye yapılan her istekte çalışır -router.use(function (req, res, next) { +router.use((req, res, next) => { console.log('Time:', Date.now()) next() }) // /user/:id yolu için yapılan herhangi bir HTTP tipi isteğinin istek bilgilerini gösteren bir ara yazılım alt-kümesi -router.use('/user/:id', function (req, res, next) { +router.use('/user/:id', (req, res, next) => { console.log('Request URL:', req.originalUrl) next() -}, function (req, res, next) { +}, (req, res, next) => { console.log('Request Type:', req.method) next() }) // /user/:id yoluna yapılan GET isteklerini işleyen bir ara yazılım alt-kümesi -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { // kullanıcı ID'si 0 ise, bir sonraki yönlendiriciye geç if (req.params.id === '0') next('route') // aksi takdirde kontrolü bu kümedeki bir sonraki ara yazılıma ver else next() -}, function (req, res, next) { +}, (req, res, next) => { // normal bir sayfa göster res.render('regular') }) // özel bir sayfa gösteren /user/:id yolu işleyicisi -router.get('/user/:id', function (req, res, next) { +router.get('/user/:id', (req, res, next) => { console.log(req.params.id) res.render('special') }) @@ -177,17 +177,17 @@ const app = express() const router = express.Router() // yönlendiriciyi bir kontrol ile doğrula ve gerektiğinde bir sonraki yönlendiriciye geçerek kurtul -router.use(function (req, res, next) { +router.use((req, res, next) => { if (!req.headers['x-auth']) return next('router') next() }) -router.get('/', function (req, res) { +router.get('/', (req, res) => { res.send('hello, user!') }) // geçen herhangi bir şey için yönlendiriciyı ve 401'i kullan -app.use('/admin', router, function (req, res) { +app.use('/admin', router, (req, res) => { res.sendStatus(401) }) ``` @@ -202,7 +202,7 @@ Hata-işleme ara yazılım fonksiyonlarını diğer ara yazılım fonksiyonları ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Bir şeyler bozuk!') }) @@ -237,7 +237,7 @@ const options = { index: false, maxAge: '1d', redirect: false, - setHeaders: function (res, path, stat) { + setHeaders (res, path, stat) { res.set('x-timestamp', Date.now()) } } diff --git a/tr/guide/using-template-engines.md b/tr/guide/using-template-engines.md index 6aade73778..c019e8f906 100644 --- a/tr/guide/using-template-engines.md +++ b/tr/guide/using-template-engines.md @@ -56,7 +56,7 @@ html Ardından, `index.pug` dosyasını işlemek için bir rota yaratın. `view engine` özelliği ayarlanmadıysa, `view` dosyasının uzantısını belirtmelisiniz. Aksi takdirde belirtmenize gerek yok. ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.render('index', { title: 'Hey', message: 'Hello there!' }) }) ``` diff --git a/tr/guide/writing-middleware.md b/tr/guide/writing-middleware.md index 78d2c5b79b..a19d70e8ec 100644 --- a/tr/guide/writing-middleware.md +++ b/tr/guide/writing-middleware.md @@ -51,7 +51,7 @@ Aşağıdaki basit bir "Merhaba Dünya" Ekspres uygulaması örneği. Bu yazın const express = require('express') const app = express() -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Merhaba Dünya!') }) @@ -86,7 +86,7 @@ const myLogger = function (req, res, next) { app.use(myLogger) -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Hello World!') }) @@ -125,9 +125,9 @@ const requestTime = function (req, res, next) { app.use(requestTime) -app.get('/', function (req, res) { +app.get('/', (req, res) => { let responseText = 'Hello World!
' - responseText += 'Requested at: ' + req.requestTime + '' + responseText += `Requested at: ${req.requestTime}` res.send(responseText) }) @@ -171,7 +171,7 @@ app.use(cookieParser()) app.use(validateCookies) // hata işleyicisi -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { res.status(400).send(err.message) }) diff --git a/tr/starter/basic-routing.md b/tr/starter/basic-routing.md index 727d9252b8..1cc24db281 100644 --- a/tr/starter/basic-routing.md +++ b/tr/starter/basic-routing.md @@ -32,7 +32,7 @@ Aşağıdaki örnekler nasıl basit bir şekilde yol tanımlayabileceğinizi gö Anasayfada `Merhaba Dünya!` ile cevap verin: ```js -app.get('/', function (req, res) { +app.get('/', (req, res) => { res.send('Merhaba Dünya!') }) ``` @@ -40,7 +40,7 @@ app.get('/', function (req, res) { Kök dizine (`/`) gelen POST isteğine bir cevap verin: ```js -app.post('/', function (req, res) { +app.post('/', (req, res) => { res.send('POST isteği geldi!') }) ``` @@ -48,7 +48,7 @@ app.post('/', function (req, res) { `/user` yoluna gelen PUT isteği: ```js -app.put('/user', function (req, res) { +app.put('/user', (req, res) => { res.send('/user adresinde bir PUT isteği') }) ``` @@ -56,7 +56,7 @@ app.put('/user', function (req, res) { `/user` yoluna gelen DELETE isteği: ```js -app.delete('/user', function (req, res) { +app.delete('/user', (req, res) => { res.send('/user adresinde bir DELETE isteği') }) ``` diff --git a/tr/starter/faq.md b/tr/starter/faq.md index 00fd0d5d0b..e60bf4616b 100644 --- a/tr/starter/faq.md +++ b/tr/starter/faq.md @@ -41,7 +41,7 @@ Daha fazla bilgi için, [Express ile görünüm motorlarını kullanmak](/{{page Express'te 404 cevapları bir hatanın sonucu olarak ortaya çıkmaz, bu yüzden hata işleyici ara katman bunları yakalamaz. Bunun sebebi 404 cevabı sadece yapılacak ekstra işin eksik olduğunu belirtir; başka bir sözle, Express tüm ara katman fonksiyonlarını ve yolları çalıştırdı, ve bunların hiçbirinin cevap döndürmediğini fark etti. Tek yapmanız gereken, bu yığının (tüm fonksiyonların) en sonuna 404'ü işleyen bir ara katman fonksiyonu yazmak: ```js -app.use(function (req, res, next) { +app.use((req, res, next) => { res.status(404).send('Üzgünüm, dosyayı bulamadım!') }) ``` @@ -53,7 +53,7 @@ Yolları dinamik olarak `express.Router()`'ın bir örneği üzerine tanımlayı Hata ile ilgili ara katman fonksiyonları da tıpkı diğer ara katman fonksiyonları gibi tanımlanır. Aradaki tek fark üç argüman yerine şu şekilde dört argüman kullanılmasıdır `(err, req, res, next)`: ```js -app.use(function (err, req, res, next) { +app.use((err, req, res, next) => { console.error(err.stack) res.status(500).send('Bir hata oluştu!') }) diff --git a/zh-cn/guide/database-integration.md b/zh-cn/guide/database-integration.md index 71df65beb9..32d15a251c 100755 --- a/zh-cn/guide/database-integration.md +++ b/zh-cn/guide/database-integration.md @@ -43,7 +43,7 @@ $ npm install cassandra-driver const cassandra = require('cassandra-driver') const client = new cassandra.Client({ contactPoints: ['localhost'] }) -client.execute('select key from system.local', function (err, result) { +client.execute('select key from system.local', (err, result) => { if (err) throw err console.log(result.rows[0]) }) @@ -66,7 +66,7 @@ const couchbase = require('couchbase') const bucket = (new couchbase.Cluster('http://localhost:8091')).openBucket('bucketName') // add a document to a bucket -bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, result) { +bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, (err, result) => { if (err) { console.log(err) } else { @@ -77,7 +77,7 @@ bucket.insert('document-key', { name: 'Matt', shoeSize: 13 }, function (err, res // get all documents with shoe size 13 const n1ql = 'SELECT d.* FROM `bucketName` d WHERE shoeSize = $1' const query = N1qlQuery.fromString(n1ql) -bucket.query(query, [13], function (err, result) { +bucket.query(query, [13], (err, result) => { if (err) { console.log(err) } else { @@ -104,7 +104,7 @@ nano.db.create('books') const books = nano.db.use('books') // Insert a book document in the books database -books.insert({ name: 'The Art of war' }, null, function (err, body) { +books.insert({ name: 'The Art of war' }, null, (err, body) => { if (err) { console.log(err) } else { @@ -113,7 +113,7 @@ books.insert({ name: 'The Art of war' }, null, function (err, body) { }) // Get a list of all books -books.list(function (err, body) { +books.list((err, body) => { if (err) { console.log(err) } else { @@ -138,13 +138,13 @@ $ npm install level levelup leveldown const levelup = require('levelup') const db = levelup('./mydb') -db.put('name', 'LevelUP', function (err) { +db.put('name', 'LevelUP', (err) => { if (err) return console.log('Ooops!', err) - db.get('name', function (err, value) { + db.get('name', (err, value) => { if (err) return console.log('Ooops!', err) - console.log('name=' + value) + console.log(`name=${value}`) }) }) ``` @@ -172,7 +172,7 @@ const connection = mysql.createConnection({ connection.connect() -connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { +connection.query('SELECT 1 + 1 AS solution', (err, rows, fields) => { if (err) throw err console.log('The solution is: ', rows[0].solution) @@ -196,10 +196,10 @@ $ npm install mongodb ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, db) => { if (err) throw err - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -212,12 +212,12 @@ MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) { ```js const MongoClient = require('mongodb').MongoClient -MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) { +MongoClient.connect('mongodb://localhost:27017/animals', (err, client) => { if (err) throw err const db = client.db('animals') - db.collection('mammals').find().toArray(function (err, result) { + db.collection('mammals').find().toArray((err, result) => { if (err) throw err console.log(result) @@ -243,10 +243,10 @@ $ npm install apoc const apoc = require('apoc') apoc.query('match (n) return n').exec().then( - function (response) { + (response) => { console.log(response) }, - function (fail) { + (fail) => { console.log(fail) } ) @@ -315,10 +315,10 @@ const pgp = require('pg-promise')(/* options */) const db = pgp('postgres://username:password@host:port/database') db.one('SELECT $1 AS value', 123) - .then(function (data) { + .then((data) => { console.log('DATA:', data.value) }) - .catch(function (error) { + .catch((error) => { console.log('ERROR:', error) }) ``` @@ -339,19 +339,19 @@ $ npm install redis const redis = require('redis') const client = redis.createClient() -client.on('error', function (err) { - console.log('Error ' + err) +client.on('error', (err) => { + console.log(`Error ${err}`) }) client.set('string key', 'string val', redis.print) client.hset('hash key', 'hashtest 1', 'some value', redis.print) client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print) -client.hkeys('hash key', function (err, replies) { - console.log(replies.length + ' replies:') +client.hkeys('hash key', (err, replies) => { + console.log(`${replies.length} replies:`) - replies.forEach(function (reply, i) { - console.log(' ' + i + ': ' + reply) + replies.forEach((reply, i) => { + console.log(` ${i}: ${reply}`) }) client.quit() @@ -387,7 +387,7 @@ const config = { const connection = new Connection(config) -connection.on('connect', function (err) { +connection.on('connect', (err) => { if (err) { console.log(err) } else { @@ -396,17 +396,17 @@ connection.on('connect', function (err) { }) function executeStatement () { - request = new Request("select 123, 'hello world'", function (err, rowCount) { + request = new Request("select 123, 'hello world'", (err, rowCount) => { if (err) { console.log(err) } else { - console.log(rowCount + ' rows') + console.log(`${rowCount} rows`) } connection.close() }) - request.on('row', function (columns) { - columns.forEach(function (column) { + request.on('row', (columns) => { + columns.forEach((column) => { if (column.value === null) { console.log('NULL') } else { @@ -435,18 +435,18 @@ $ npm install sqlite3 const sqlite3 = require('sqlite3').verbose() const db = new sqlite3.Database(':memory:') -db.serialize(function () { +db.serialize(() => { db.run('CREATE TABLE lorem (info TEXT)') const stmt = db.prepare('INSERT INTO lorem VALUES (?)') for (let i = 0; i < 10; i++) { - stmt.run('Ipsum ' + i) + stmt.run(`Ipsum ${i}`) } stmt.finalize() - db.each('SELECT rowid AS id, info FROM lorem', function (err, row) { - console.log(row.id + ': ' + row.info) + db.each('SELECT rowid AS id, info FROM lorem', (err, row) => { + console.log(`${row.id}: ${row.info}`) }) }) @@ -482,9 +482,9 @@ client.search({ } } } -}).then(function (response) { +}).then((response) => { const hits = response.hits.hits -}, function (error) { +}, (error) => { console.trace(error.message) }) ```