diff --git a/.eslintignore b/.eslintignore index 0a78c7ae867ad..dd6fec1664e68 100644 --- a/.eslintignore +++ b/.eslintignore @@ -2,3 +2,5 @@ static/legacy/ external/ build/ +# Top level await isn't supported till ESLint 8 +locale/en/blog/release/v17.0.0.md diff --git a/.eslintrc b/.eslintrc index 12580d0535d54..6d4d41151c94b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -9,5 +9,38 @@ ], "rules": { "prettier/prettier": "error" - } + }, + "overrides": [ + { + "files": [ + "**/*.md" + ], + "plugins": [ + "markdown" + ], + "processor": "markdown/markdown" + }, + { + "files": [ + "**/*.md/*.js" + ], + "rules": { + "eqeqeq": "off", + "no-const-assign": "off", + "no-undef": "off", + "no-unused-expressions": "off", + "no-unused-vars": "off", + "node/handle-callback-err": "off", + "node/no-deprecated-api": "off", + "prefer-const": "off", + "prettier/prettier": [ + "error", + { + "singleQuote": true, + "trailingComma": "none" + } + ] + } + } + ] } diff --git a/locale/en/blog/release/v12.16.0.md b/locale/en/blog/release/v12.16.0.md index 535b0ec46e16c..5ded2902fdcef 100644 --- a/locale/en/blog/release/v12.16.0.md +++ b/locale/en/blog/release/v12.16.0.md @@ -130,7 +130,6 @@ The new `EventEmitter.on` static method allows to async iterate over events: const { on, EventEmitter } = require('events'); (async () => { - const ee = new EventEmitter(); // Emit later on @@ -145,7 +144,6 @@ const { on, EventEmitter } = require('events'); // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } - })(); ``` diff --git a/locale/en/blog/release/v12.17.0.md b/locale/en/blog/release/v12.17.0.md index df59f6e3ecee7..2f401a8754ec2 100644 --- a/locale/en/blog/release/v12.17.0.md +++ b/locale/en/blog/release/v12.17.0.md @@ -62,16 +62,18 @@ function logWithId(msg) { } let idSeq = 0; -http.createServer((req, res) => { - asyncLocalStorage.run(idSeq++, () => { - logWithId('start'); - // Imagine any chain of async operations here. - setImmediate(() => { - logWithId('finish'); - res.end(); +http + .createServer((req, res) => { + asyncLocalStorage.run(idSeq++, () => { + logWithId('start'); + // Imagine any chain of async operations here. + setImmediate(() => { + logWithId('finish'); + res.end(); + }); }); - }); -}).listen(8080); + }) + .listen(8080); ``` In this example, the `logWithId` function will always know what the current diff --git a/locale/en/blog/release/v14.17.0.md b/locale/en/blog/release/v14.17.0.md index 2c5fdf5402e43..ad565ba0bc6f1 100644 --- a/locale/en/blog/release/v14.17.0.md +++ b/locale/en/blog/release/v14.17.0.md @@ -27,7 +27,7 @@ MySQL.prototype.query = function query(queryString, values, callback) { // Broadcast query information whenever a query is made channel.publish({ query: queryString, - host: this.hostname, + host: this.hostname }); this.doQuery(queryString, values, callback); diff --git a/locale/en/blog/release/v15.1.0.md b/locale/en/blog/release/v15.1.0.md index 266ffa6e5406d..e662f4ed43e30 100644 --- a/locale/en/blog/release/v15.1.0.md +++ b/locale/en/blog/release/v15.1.0.md @@ -24,7 +24,7 @@ MySQL.prototype.query = function query(queryString, values, callback) { // Broadcast query information whenever a query is made channel.publish({ query: queryString, - host: this.hostname, + host: this.hostname }); this.doQuery(queryString, values, callback); diff --git a/locale/en/blog/release/v8.0.0.md b/locale/en/blog/release/v8.0.0.md index 6582485ad4fdb..47c07f6c8fa96 100644 --- a/locale/en/blog/release/v8.0.0.md +++ b/locale/en/blog/release/v8.0.0.md @@ -153,8 +153,12 @@ const util = require('util'); const readfile = util.promisify(fs.readFile); readfile('/some/file') - .then((data) => { /** ... **/ }) - .catch((err) => { /** ... **/ }); + .then((data) => { + /** ... **/ + }) + .catch((err) => { + /** ... **/ + }); ``` ### Console changes @@ -183,7 +187,7 @@ Codes are manifest to the user in two ways: For instance, calling `assert(false)` will generate the following `AssertionError`: -```js +```shell > assert(false) AssertionError [ERR_ASSERTION]: false == true at repl:1:1 @@ -240,7 +244,9 @@ const session = new inspector.Session(); session.connect(); // Listen for inspector events -session.on('inspectorNotification', (message) => { /** ... **/ }); +session.on('inspectorNotification', (message) => { + /** ... **/ +}); // Send messages to the inspector session.post(message); diff --git a/locale/en/docs/guides/buffer-constructor-deprecation.md b/locale/en/docs/guides/buffer-constructor-deprecation.md index cc8f703679bf4..7eca7f7393427 100644 --- a/locale/en/docs/guides/buffer-constructor-deprecation.md +++ b/locale/en/docs/guides/buffer-constructor-deprecation.md @@ -186,7 +186,7 @@ compiles to. For Node.js 0.10.x (and below) support: ```js -var buf; +let buf; if (Buffer.alloc) { buf = Buffer.alloc(number); } else { diff --git a/locale/en/docs/guides/domain-postmortem.md b/locale/en/docs/guides/domain-postmortem.md index c9a6df9906710..9e7e32a94c478 100644 --- a/locale/en/docs/guides/domain-postmortem.md +++ b/locale/en/docs/guides/domain-postmortem.md @@ -24,7 +24,9 @@ const c = require('./c'); // module b.js const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); +d.on('error', () => { + /* silence everything */ +}); d.enter(); // module c.js @@ -57,10 +59,14 @@ const net = require('net'); const d = domain.create(); d.on('error', (err) => console.error(err.message)); -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); +d.run(() => + net + .createServer((c) => { + c.end(); + c.write('bye'); + }) + .listen(8000) +); ``` Even manually removing the connection via `d.remove(c)` does not prevent the @@ -77,17 +83,19 @@ const d = domain.create(); d.on('error', () => console.error('d intercepted an error')); d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); + const server = net + .createServer((c) => { + const e = domain.create(); // No 'error' handler being set. + e.run(() => { + // This will not be caught by d's error handler. + setImmediate(() => { + throw new Error('thrown from setImmediate'); + }); + // Though this one will bubble to d's error handler. + throw new Error('immediately thrown'); }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); + }) + .listen(8080); }); ``` @@ -118,21 +126,25 @@ example of the failing of error propagation: ```js const d1 = domain.create(); d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); +d1.on('error', (er) => { + /* handle error */ +}); -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { +d1.run(() => + setTimeout(() => { + const d2 = domain.create(); + d2.bar = 43; + d2.on('error', (er) => console.error(er.message, domain._stack)); + d2.run(() => { setTimeout(() => { - throw new Error('outer'); + setTimeout(() => { + throw new Error('outer'); + }); + throw new Error('inner'); }); - throw new Error('inner'); }); - }); -})); + }) +); ``` Even in the case that the domain instances are being used for local storage so @@ -176,8 +188,7 @@ let uid = 0; // Setting up temporary resources const buf = Buffer.alloc(FILESIZE); -for (let i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII +for (let i = 0; i < buf.length; i++) buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII fs.writeFileSync(FILENAME, buf); function ConnectionResource(c) { @@ -185,7 +196,7 @@ function ConnectionResource(c) { this._connection = c; this._alive = true; this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); + this._id = Math.random().toString(32).substr(2).substr(0, 8) + ++uid; this._domain.add(c); this._domain.on('error', () => { @@ -214,18 +225,24 @@ ConnectionResource.prototype.write = function write(chunk) { }; // Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); +net + .createServer((c) => { + const cr = new ConnectionResource(c); - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); + const d1 = domain.create(); + fs.open( + FILENAME, + 'r', + d1.intercept((fd) => { + streamInParts(fd, cr, 0); + }) + ); - pipeData(cr); + pipeData(cr); - c.on('close', () => cr.end()); -}).listen(8080); + c.on('close', () => cr.end()); + }) + .listen(8080); function streamInParts(fd, cr, pos) { const d2 = domain.create(); @@ -234,24 +251,33 @@ function streamInParts(fd, cr, pos) { print('d2 error:', er.message); cr.end(); }); - fs.read(fd, Buffer.alloc(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); + fs.read( + fd, + Buffer.alloc(10), + 0, + 10, + pos, + d2.intercept((bRead, buf) => { + if (!cr.isAlive()) { + return fs.close(fd); } - return; - } - cr.end(buf); - fs.close(fd); - })); + if (cr._connection.bytesWritten < FILESIZE) { + // Documentation says callback is optional, but doesn't mention that if + // the write fails an exception will be thrown. + const goodtogo = cr.write(buf); + if (goodtogo) { + setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); + } else { + cr._connection.once('drain', () => + streamInParts(fd, cr, pos + bRead) + ); + } + return; + } + cr.end(buf); + fs.close(fd); + }) + ); } function pipeData(cr) { @@ -293,9 +319,8 @@ process.on('exit', () => { fs.unlinkSync(pipeList[i]); } fs.unlinkSync(FILENAME); - } catch (e) { } + } catch (e) {} }); - ``` * When a new connection happens, concurrently: @@ -344,18 +369,20 @@ propagate data along asynchronous stacks: const domain = require('domain'); const net = require('net'); -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log('listening on 8080')); +const server = net + .createServer((c) => { + // Use a domain to propagate data across events within the + // connection so that we don't have to pass arguments + // everywhere. + const d = domain.create(); + d.data = { connection: c }; + d.add(c); + // Mock class that does some useless async data transformation + // for demonstration purposes. + const ds = new DataStream(dataTransformed); + c.on('data', (chunk) => ds.data(chunk)); + }) + .listen(8080, () => console.log('listening on 8080')); function dataTransformed(chunk) { // FAIL! Because the DataStream instance also created a diff --git a/locale/en/docs/guides/event-loop-timers-and-nexttick.md b/locale/en/docs/guides/event-loop-timers-and-nexttick.md index fcf0fe78c97d7..54e6a4710f531 100644 --- a/locale/en/docs/guides/event-loop-timers-and-nexttick.md +++ b/locale/en/docs/guides/event-loop-timers-and-nexttick.md @@ -311,8 +311,10 @@ it doesn't have to be. Take this code snippet for example: ```js function apiCall(arg, callback) { if (typeof arg !== 'string') - return process.nextTick(callback, - new TypeError('argument should be string')); + return process.nextTick( + callback, + new TypeError('argument should be string') + ); } ``` @@ -338,7 +340,9 @@ Take this snippet for example: let bar; // this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall(callback) { callback(); } +function someAsyncApiCall(callback) { + callback(); +} // the callback is called before `someAsyncApiCall` completes. someAsyncApiCall(() => { @@ -427,10 +431,10 @@ One example is to match the user's expectations. Simple example: ```js const server = net.createServer(); -server.on('connection', (conn) => { }); +server.on('connection', (conn) => {}); server.listen(8080); -server.on('listening', () => { }); +server.on('listening', () => {}); ``` Say that `listen()` is run at the beginning of the event loop, but the diff --git a/locale/en/knowledge/HTTP/clients/how-to-access-query-string-parameters.md b/locale/en/knowledge/HTTP/clients/how-to-access-query-string-parameters.md index 34ae95a92070d..34c3676106bad 100644 --- a/locale/en/knowledge/HTTP/clients/how-to-access-query-string-parameters.md +++ b/locale/en/knowledge/HTTP/clients/how-to-access-query-string-parameters.md @@ -13,13 +13,15 @@ In Node.js, functionality to aid in the accessing of URL query string parameters const http = require('http'); const url = require('url'); -http.createServer(function (req, res) { - const queryObject = url.parse(req.url,true).query; - console.log(queryObject); - - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end('Feel free to add query parameters to the end of the url'); -}).listen(8080); +http + .createServer(function (req, res) { + const queryObject = url.parse(req.url, true).query; + console.log(queryObject); + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end('Feel free to add query parameters to the end of the url'); + }) + .listen(8080); ``` > To test this code run `node app.js` (app.js is name of the file) on the terminal and then go to your browser and type `http://localhost:8080/app.js?foo=bad&baz=foo` on the URL bar @@ -43,8 +45,8 @@ This method, however, must be passed just a querystring portion of a url. Passin ```js const querystring = require('querystring'); -const url = "http://example.com/index.html?code=string&key=12&id=false"; -const qs = "code=string&key=12&id=false"; +const url = 'http://example.com/index.html?code=string&key=12&id=false'; +const qs = 'code=string&key=12&id=false'; console.log(querystring.parse(qs)); // > { code: 'string', key: '12', id: 'false' } diff --git a/locale/en/knowledge/REPL/how-to-create-a-custom-repl.md b/locale/en/knowledge/REPL/how-to-create-a-custom-repl.md index 63705424eded9..853ef4f2e74ee 100644 --- a/locale/en/knowledge/REPL/how-to-create-a-custom-repl.md +++ b/locale/en/knowledge/REPL/how-to-create-a-custom-repl.md @@ -11,7 +11,7 @@ layout: knowledge-post.hbs Node.js allows users to create their own REPLs with the [repl module](https://nodejs.org/api/repl.html). Its basic use looks like this: ```js -var repl = require('repl') +const repl = require('repl'); repl.start(prompt, stream); ``` @@ -23,26 +23,28 @@ However, the repl is pretty flexible. Here's an example that shows this off: ```js #!/usr/bin/env node -var net = require("net"); -var repl = require("repl"); +const net = require('net'); +const repl = require('repl'); -var mood = function () { - var m = [ "^__^", "-___-;", ">.<", "<_>" ]; - return m[Math.floor(Math.random()*m.length)]; +const mood = function () { + const m = ['^__^', '-___-;', '>.<', '<_>']; + return m[Math.floor(Math.random() * m.length)]; }; -//A remote node repl that you can telnet to! -net.createServer(function (socket) { - var remote = repl.start("node::remote> ", socket); - //Adding "mood" and "bonus" to the remote REPL's context. - remote.context.mood = mood; - remote.context.bonus = "UNLOCKED"; -}).listen(5001); +// A remote node repl that you can telnet to! +net + .createServer(function (socket) { + const remote = repl.start('node::remote> ', socket); + // Adding "mood" and "bonus" to the remote REPL's context. + remote.context.mood = mood; + remote.context.bonus = 'UNLOCKED'; + }) + .listen(5001); -console.log("Remote REPL started on port 5001."); +console.log('Remote REPL started on port 5001.'); -//A "local" node repl with a custom prompt -var local = repl.start("node::local> "); +// A "local" node repl with a custom prompt +const local = repl.start('node::local> '); // Exposing the function "mood" to the local REPL's context. local.context.mood = mood; diff --git a/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md b/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md index e8d0dfa626ec3..6ace3ae1f9c3c 100644 --- a/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md +++ b/locale/en/knowledge/advanced/buffers/how-to-use-buffers.md @@ -34,7 +34,7 @@ In the wild, buffers are usually seen in the context of binary data coming from There are a few ways to create new buffers: ```js -var buffer = Buffer.alloc(8); +const buffer = Buffer.alloc(8); // This will print out 8 bytes of zero: // ``` @@ -42,7 +42,7 @@ var buffer = Buffer.alloc(8); This buffer is initialized and contains 8 bytes of zero. ```js -var buffer = Buffer.from([ 8, 6, 7, 5, 3, 0, 9]); +const buffer = Buffer.from([8, 6, 7, 5, 3, 0, 9]); // This will print out 8 bytes of certain values: // ``` @@ -50,7 +50,7 @@ var buffer = Buffer.from([ 8, 6, 7, 5, 3, 0, 9]); This initializes the buffer to the contents of this array. Keep in mind that the contents of the array are integers representing bytes. ```js -var buffer = Buffer.from("I'm a string!", "utf-8"); +const buffer = Buffer.from("I'm a string!", 'utf-8'); // This will print out a chain of values in utf-8: // ``` diff --git a/locale/en/knowledge/child-processes/how-to-spawn-a-child-process.md b/locale/en/knowledge/child-processes/how-to-spawn-a-child-process.md index 245d5d8f7479a..1658471a674b0 100644 --- a/locale/en/knowledge/child-processes/how-to-spawn-a-child-process.md +++ b/locale/en/knowledge/child-processes/how-to-spawn-a-child-process.md @@ -22,15 +22,15 @@ const { exec } = require('child_process'); const ls = exec('ls -l', function (error, stdout, stderr) { if (error) { console.log(error.stack); - console.log('Error code: '+error.code); - console.log('Signal received: '+error.signal); + console.log('Error code: ' + error.code); + console.log('Signal received: ' + error.signal); } - console.log('Child Process STDOUT: '+stdout); - console.log('Child Process STDERR: '+stderr); + console.log('Child Process STDOUT: ' + stdout); + console.log('Child Process STDERR: ' + stderr); }); ls.on('exit', function (code) { - console.log('Child process exited with exit code '+code); + console.log('Child process exited with exit code ' + code); }); ``` diff --git a/locale/en/knowledge/command-line/how-to-get-colors-on-the-command-line.md b/locale/en/knowledge/command-line/how-to-get-colors-on-the-command-line.md index eb876efc1b02b..a14a7fbf33aed 100644 --- a/locale/en/knowledge/command-line/how-to-get-colors-on-the-command-line.md +++ b/locale/en/knowledge/command-line/how-to-get-colors-on-the-command-line.md @@ -45,7 +45,7 @@ The last pair of `console.log` statements are probably the most important. Becau Let's look at a more explicit example. If you set the following properties with `colors.js`: ```js -myString.red.blue.green +myString.red.blue.green; ``` You can think of your terminal saying to itself, "Make this green. No, make this blue. No, make this red. No more color codes now? Red it is, then." The codes are read in the reverse order, and the last/'innermost' is applied. This can be extremely useful if you're using a library that sets its own default colors that you don't like - if you set a color code yourself on the string you pass in to the library, it will supersede the other author's color code(s). @@ -79,7 +79,7 @@ Unlike the `String.prototype` approach, the chained methods on the `colors` inst With the latest version of `colors.js` you can also define **[Custom Themes](https://www.npmjs.com/package/colors#custom-themes)** in `color.js`, which makes our code more Robust and allows better Encapsulation of data. A nice use case of this maybe: ```js -var colors = require('colors'); +const colors = require('colors'); colors.setTheme({ info: 'bgGreen', @@ -90,10 +90,10 @@ colors.setTheme({ }); // outputs red text -console.log("this is an error".error); +console.log('this is an error'.error); // outputs text on blue background -console.log("this is a success message".success); +console.log('this is a success message'.success); ``` One last thing: the colors can look quite different in different terminals - sometimes, `bold` is bold, sometimes it's just a different color. Try it out and see for yourself! diff --git a/locale/en/knowledge/command-line/how-to-parse-command-line-arguments.md b/locale/en/knowledge/command-line/how-to-parse-command-line-arguments.md index cbd9be619fd87..3a92d920e2c79 100644 --- a/locale/en/knowledge/command-line/how-to-parse-command-line-arguments.md +++ b/locale/en/knowledge/command-line/how-to-parse-command-line-arguments.md @@ -33,7 +33,7 @@ There you have it - an array containing any arguments you passed in. Notice the Where everyday CLI arguments are concerned, you'll want to skip the first two. Now try this in `argv.js`: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); ``` @@ -47,17 +47,17 @@ myArgs: [ 'one', 'two', 'three', 'four', 'five' ] Now let's actually do something with the args: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); switch (myArgs[0]) { -case 'insult': + case 'insult': console.log(myArgs[1], 'smells quite badly.'); break; -case 'compliment': + case 'compliment': console.log(myArgs[1], 'is really cool.'); break; -default: + default: console.log('Sorry, that is not something I know how to do.'); } ``` @@ -78,33 +78,32 @@ Once you have it, give it a try - it can really be a life-saver. Lets test it wi const yargs = require('yargs'); const argv = yargs - .command('lyr', 'Tells whether an year is leap year or not', { - year: { - description: 'the year to check for', - alias: 'y', - type: 'number', - } - }) - .option('time', { - alias: 't', - description: 'Tell the present Time', - type: 'boolean', - }) - .help() - .alias('help', 'h') - .argv; + .command('lyr', 'Tells whether an year is leap year or not', { + year: { + description: 'the year to check for', + alias: 'y', + type: 'number' + } + }) + .option('time', { + alias: 't', + description: 'Tell the present Time', + type: 'boolean' + }) + .help() + .alias('help', 'h').argv; if (argv.time) { - console.log('The current time is: ', new Date().toLocaleTimeString()); + console.log('The current time is: ', new Date().toLocaleTimeString()); } if (argv._.includes('lyr')) { - const year = argv.year || new Date().getFullYear(); - if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { - console.log(`${year} is a Leap Year`); - } else { - console.log(`${year} is NOT a Leap Year`); - } + const year = argv.year || new Date().getFullYear(); + if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { + console.log(`${year} is a Leap Year`); + } else { + console.log(`${year} is NOT a Leap Year`); + } } console.log(argv); diff --git a/locale/en/knowledge/command-line/how-to-prompt-for-command-line-input.md b/locale/en/knowledge/command-line/how-to-prompt-for-command-line-input.md index 41d2b189fddcf..e76b67f7bcae3 100644 --- a/locale/en/knowledge/command-line/how-to-prompt-for-command-line-input.md +++ b/locale/en/knowledge/command-line/how-to-prompt-for-command-line-input.md @@ -16,22 +16,22 @@ Streams are the Node.js way of dealing with evented I/O - it's a big topic, and Here's a simple example. Try the following in a new file: ```js -const readline = require("readline"); +const readline = require('readline'); const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout + input: process.stdin, + output: process.stdout }); -rl.question("What is your name ? ", function(name) { - rl.question("Where do you live ? ", function(country) { - console.log(`${name}, is a citizen of ${country}`); - rl.close(); - }); +rl.question('What is your name ? ', function (name) { + rl.question('Where do you live ? ', function (country) { + console.log(`${name}, is a citizen of ${country}`); + rl.close(); + }); }); -rl.on("close", function() { - console.log("\nBYE BYE !!!"); - process.exit(0); +rl.on('close', function () { + console.log('\nBYE BYE !!!'); + process.exit(0); }); ``` @@ -57,15 +57,17 @@ const prompt = require('prompt'); prompt.start(); prompt.get(['username', 'email'], function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Email: ' + result.email); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Email: ' + result.email); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` @@ -77,29 +79,31 @@ Prompt also makes it trivial to handle a certain set of recurring properties tha const prompt = require('prompt'); const properties = [ - { - name: 'username', - validator: /^[a-zA-Z\s\-]+$/, - warning: 'Username must be only letters, spaces, or dashes' - }, - { - name: 'password', - hidden: true - } + { + name: 'username', + validator: /^[a-zA-Z\s-]+$/, + warning: 'Username must be only letters, spaces, or dashes' + }, + { + name: 'password', + hidden: true + } ]; prompt.start(); prompt.get(properties, function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Password: ' + result.password); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Password: ' + result.password); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` diff --git a/locale/en/knowledge/cryptography/how-to-use-crypto-module.md b/locale/en/knowledge/cryptography/how-to-use-crypto-module.md index 01b7be3af8361..c26c235c6dbbc 100644 --- a/locale/en/knowledge/cryptography/how-to-use-crypto-module.md +++ b/locale/en/knowledge/cryptography/how-to-use-crypto-module.md @@ -37,10 +37,10 @@ One of the most common hash algorithms is [SHA-256](https://en.wikipedia.org/wik Crypto has a method called `createHash` which allows you to calculate a hash. Its only argument is a string representing the hash. This example finds the SHA-256 hash for the string, "Man oh man do I love node!": ```js -require("crypto") - .createHash("sha256") - .update("Man oh man do I love node!") - .digest("hex"); +require('crypto') + .createHash('sha256') + .update('Man oh man do I love node!') + .digest('hex'); ``` The `update` method is used to push data to later be turned into a hash with the `digest` method. `update` can be invoked multiple times to ingest streaming data, such as buffers from a file read stream. The argument for `digest` represents the output format, and may either be "binary", "hex" or "base64". It defaults to binary. @@ -52,9 +52,10 @@ HMAC stands for Hash-based Message Authentication Code, and is a process for app The API for hmacs is very similar to that of `createHash`, except that the method is called `createHmac` and it takes a key as a second argument: ```js -require("crypto").createHmac("sha256", "password") +require('crypto') + .createHmac('sha256', 'password') .update("If you love node so much why don't you marry it?") - .digest("hex"); + .digest('hex'); ``` The resulting SHA-256 hash is unique to both the input data and the key. @@ -83,45 +84,35 @@ Here's an example, slightly less trivial than previous examples, that uses crypt ```js #!/usr/bin/env node -const crypto = require('crypto'), - argv = require("yargs").argv, - resizedIV = Buffer.allocUnsafe(16), - iv = crypto - .createHash("sha256") - .update("myHashedIV") - .digest(); +const crypto = require('crypto'); +const argv = require('yargs').argv; +const resizedIV = Buffer.allocUnsafe(16); +const iv = crypto.createHash('sha256').update('myHashedIV').digest(); iv.copy(resizedIV); if (argv.e && argv.key) { - const key = crypto - .createHash("sha256") - .update(argv.key) - .digest(), - cipher = crypto.createCipheriv("aes256", key, resizedIV), - msg = []; + const key = crypto.createHash('sha256').update(argv.key).digest(); + const cipher = crypto.createCipheriv('aes256', key, resizedIV); + const msg = []; - argv._.forEach( function (phrase) { - msg.push(cipher.update(phrase, "binary", "hex")); - }); - - msg.push(cipher.final("hex")); - console.log(msg.join("")); + argv._.forEach(function (phrase) { + msg.push(cipher.update(phrase, 'binary', 'hex')); + }); + msg.push(cipher.final('hex')); + console.log(msg.join('')); } else if (argv.d && argv.key) { - const key = crypto - .createHash("sha256") - .update(argv.key) - .digest(), - decipher = crypto.createDecipheriv("aes256", key, resizedIV), - msg = []; - - argv._.forEach( function (phrase) { - msg.push(decipher.update(phrase, "hex", "binary")); - }); - - msg.push(decipher.final("binary")); - console.log(msg.join("")); + const key = crypto.createHash('sha256').update(argv.key).digest(); + const decipher = crypto.createDecipheriv('aes256', key, resizedIV); + const msg = []; + + argv._.forEach(function (phrase) { + msg.push(decipher.update(phrase, 'hex', 'binary')); + }); + + msg.push(decipher.final('binary')); + console.log(msg.join('')); } ``` diff --git a/locale/en/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md b/locale/en/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md index e024451e47d41..a4e6dc638128a 100644 --- a/locale/en/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md +++ b/locale/en/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md @@ -13,10 +13,10 @@ Usually a function will take a set number of parameters, and require that all of ```js const pow = (base, power = 2) => { return Math.pow(base, power); -} +}; console.log(pow(2)); // 4 -console.log(pow(2,10)); // 1024 +console.log(pow(2, 10)); // 1024 ``` In the above code The function `pow` return square of a number or any other power specified in the function call because the argument `power` is given a default value of 2 so whenever no second argument is provided or the provided value is `undefined` the function `pow` will use 2 as the value of argument `power`. But there is a small gotcha in it: @@ -24,7 +24,7 @@ In the above code The function `pow` return square of a number or any other powe ```js const pow = (base, power = 2) => { return Math.pow(base, power); -} +}; console.log(pow(2, undefined)); // 4 console.log(pow(2, null)); // 1 @@ -40,28 +40,28 @@ The first idiom is giving a default value for the last parameter. This is done b ```js const example = function (optionalArg) { - optionalArg = optionalArg || "No parameter was passed"; + optionalArg = optionalArg || 'No parameter was passed'; console.log(optionalArg); -} +}; const betterExample = function (optionalArg) { if (optionalArg === undefined) { - optionalArg = "No parameter was passed"; + optionalArg = 'No parameter was passed'; } console.log(optionalArg); -} +}; -console.log("Without parameter:"); +console.log('Without parameter:'); example(); betterExample(); -console.log("\nWith parameter:"); -example("parameter was passed"); -betterExample("parameter was passed"); +console.log('\nWith parameter:'); +example('parameter was passed'); +betterExample('parameter was passed'); -console.log("\nEmpty String:"); -example(""); -betterExample(""); +console.log('\nEmpty String:'); +example(''); +betterExample(''); ``` The second idiom is when the optional value is in the middle it can cause some undesired effects since all the parameters are shifted over. The optional parameter is not the `undefined` value in this case - the last parameter is the `undefined` one. So you have to check if the last parameter is `undefined` and then manually fix all the other parameters before continuing in the code. This case is also valid for modern JavaScript(ES6/ES2015). The example shows you how to do that: @@ -72,12 +72,16 @@ const example = function (param1, optParam, callback) { // only two parameters were passed, so the callback is actually in `optParam` callback = optParam; - //give `optParam` a default value - optParam = "and a default parameter"; + // give `optParam` a default value + optParam = 'and a default parameter'; } callback(param1, optParam); -} - -example("This is a necessary parameter", console.log); -example("This is a necessary parameter", "and an optional parameter", console.log); +}; + +example('This is a necessary parameter', console.log); +example( + 'This is a necessary parameter', + 'and an optional parameter', + console.log +); ``` diff --git a/locale/en/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md b/locale/en/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md index 52e993be22934..e5f1d7142bce5 100644 --- a/locale/en/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md +++ b/locale/en/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md @@ -12,8 +12,12 @@ layout: knowledge-post.hbs There are two most common built-in timer functions, `setTimeout` and `setInterval`, which can be used to call a function at a later time. For an example usage: ```js -setTimeout(function() { console.log("setTimeout: It's been one second!"); }, 1000); -setInterval(function() { console.log("setInterval: It's been one second!"); }, 1000); +setTimeout(function () { + console.log("setTimeout: It's been one second!"); +}, 1000); +setInterval(function () { + console.log("setInterval: It's been one second!"); +}, 1000); ``` An example output is: @@ -39,9 +43,9 @@ This can cause problems, however, if your server is slow and it takes, for examp ```js const recursive = function () { - console.log("It has been one second!"); - setTimeout(recursive,1000); -} + console.log('It has been one second!'); + setTimeout(recursive, 1000); +}; recursive(); ``` @@ -50,12 +54,12 @@ As you can see, it makes a call to the `recursive` function which, as it complet You can clear the timers you set with `clearTimeout` and `clearInterval`. Their usages are very simple: ```js -function never_call () { - console.log("You should never call this function"); +function neverCall() { + console.log('You should never call this function'); } -const id1 = setTimeout(never_call,1000); -const id2 = setInterval(never_call,1000); +const id1 = setTimeout(neverCall, 1000); +const id2 = setInterval(neverCall, 1000); clearTimeout(id1); clearInterval(id2); @@ -66,8 +70,8 @@ So if you keep track of the return values of the timers, you can easily unhook t The final trick for the timer objects is you can pass parameters to the callback by passing more parameters to setTimeout and setInterval: ```js -setTimeout(console.log, 1000, "This", "has", 4, "parameters"); -setInterval(console.log, 1000, "This only has one"); +setTimeout(console.log, 1000, 'This', 'has', 4, 'parameters'); +setInterval(console.log, 1000, 'This only has one'); ``` The output is: @@ -87,9 +91,9 @@ This only has one `setImmediate()` is another built-in timer function which as the name suggest, runs immediately after the first iteration of the event loop is completed. In other words, `setImmediate()` is similar to a `setTimeout()` function with a `0ms` delay. The `setImmediate()` function can also take extra parameters that are passed when the callback is called: ```js -console.log("This will be printed first"); -setImmediate(console.log, "This is an extra parameter"); -console.log("This will be printed second"); +console.log('This will be printed first'); +setImmediate(console.log, 'This is an extra parameter'); +console.log('This will be printed second'); ``` The output is: diff --git a/locale/en/knowledge/javascript-conventions/what-is-json.md b/locale/en/knowledge/javascript-conventions/what-is-json.md index bc65817b88ed3..e991db5b1199a 100644 --- a/locale/en/knowledge/javascript-conventions/what-is-json.md +++ b/locale/en/knowledge/javascript-conventions/what-is-json.md @@ -33,10 +33,10 @@ serialized string in the JSON format. ```js const data = { - name: "John Doe", + name: 'John Doe', age: 32, - title: "Vice President of JavaScript" -} + title: 'Vice President of JavaScript' +}; const jsonStr = JSON.stringify(data); @@ -49,7 +49,8 @@ console.log(jsonStr); structure. ```js -const jsonStr = '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'; +const jsonStr = + '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'; const data = JSON.parse(jsonStr); diff --git a/locale/en/knowledge/javascript-conventions/what-is-the-arguments-object.md b/locale/en/knowledge/javascript-conventions/what-is-the-arguments-object.md index ba390d5e20c8b..de24e4609c6cb 100644 --- a/locale/en/knowledge/javascript-conventions/what-is-the-arguments-object.md +++ b/locale/en/knowledge/javascript-conventions/what-is-the-arguments-object.md @@ -24,11 +24,11 @@ property of `arguments` is callee, which ES5 forbids to use in `strict mode` mor properties of `arguments`. ```js -const myfunc = function(one) { +const myfunc = function (one) { arguments[0] === one; arguments[1] === 2; arguments.length === 3; -} +}; myfunc(1, 2, 3); ``` @@ -41,10 +41,10 @@ methods, e.g. `arguments.sort()` raises a TypeError. Instead, you need to copy the values into a true array first. With the advent of ES6 `Array.from()` method this is quite straightforward. ```js -const myfunc = function(a, b, c) { +const myfunc = function (a, b, c) { const args = Array.from(arguments); - console.log(args) // [1, 2, 3] -} + console.log(args); // [1, 2, 3] +}; myfunc(1, 2, 3); ``` @@ -58,10 +58,10 @@ invoked using call or apply. This technique also suggests another way to convert `arguments` into a true array using the `Array.slice` method. ```js -myfunc.apply(obj, arguments). - -// concat arguments onto the -Array.prototype.concat.apply([1,2,3], arguments); +myfunc + .apply(obj, arguments) + // concat arguments onto the + .Array.prototype.concat.apply([1, 2, 3], arguments); // turn arguments into a true array const args = Array.prototype.slice.call(arguments); @@ -77,7 +77,7 @@ The `arrow functions` were added in the ECMAScript 2015 (ES6) specification as a ```js const myfunc = (...args) => { console.log('first parameter is ', args[0]); -} +}; myfunc(1, 2, 3); ``` diff --git a/locale/es/docs/guides/buffer-constructor-deprecation.md b/locale/es/docs/guides/buffer-constructor-deprecation.md index ee1d5a8e2dd2c..2e8f906868a7f 100644 --- a/locale/es/docs/guides/buffer-constructor-deprecation.md +++ b/locale/es/docs/guides/buffer-constructor-deprecation.md @@ -141,7 +141,7 @@ Also, note that using TypeScript does not fix this problem for you — when libs For Node.js 0.10.x (and below) support: ```js -var buf; +let buf; if (Buffer.alloc) { buf = Buffer.alloc(number); } else { diff --git a/locale/es/docs/guides/domain-postmortem.md b/locale/es/docs/guides/domain-postmortem.md index 243b24a9e7603..5b26173fa7c13 100644 --- a/locale/es/docs/guides/domain-postmortem.md +++ b/locale/es/docs/guides/domain-postmortem.md @@ -20,7 +20,9 @@ const c = require('./c'); // module b.js const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); +d.on('error', () => { + /* silence everything */ +}); d.enter(); // module c.js @@ -40,10 +42,14 @@ const net = require('net'); const d = domain.create(); d.on('error', (err) => console.error(err.message)); -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); +d.run(() => + net + .createServer((c) => { + c.end(); + c.write('bye'); + }) + .listen(8000) +); ``` Even manually removing the connection via `d.remove(c)` does not prevent the connection's error from being automatically intercepted. @@ -57,17 +63,19 @@ const d = domain.create(); d.on('error', () => console.error('d intercepted an error')); d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); + const server = net + .createServer((c) => { + const e = domain.create(); // No 'error' handler being set. + e.run(() => { + // This will not be caught by d's error handler. + setImmediate(() => { + throw new Error('thrown from setImmediate'); + }); + // Though this one will bubble to d's error handler. + throw new Error('immediately thrown'); }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); + }) + .listen(8080); }); ``` @@ -84,21 +92,25 @@ Propagating errors across nested domains is not straight forward, if even possib ```js const d1 = domain.create(); d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); +d1.on('error', (er) => { + /* handle error */ +}); -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { +d1.run(() => + setTimeout(() => { + const d2 = domain.create(); + d2.bar = 43; + d2.on('error', (er) => console.error(er.message, domain._stack)); + d2.run(() => { setTimeout(() => { - throw new Error('outer'); + setTimeout(() => { + throw new Error('outer'); + }); + throw new Error('inner'); }); - throw new Error('inner'); }); - }); -})); + }) +); ``` Even in the case that the domain instances are being used for local storage so access to resources are made available there is still no way to allow the error to continue propagating from `d2` back to `d1`. Quick inspection may tell us that simply throwing from `d2`'s domain `'error'` handler would allow `d1` to then catch the exception and execute its own error handler. Though that is not the case. Upon inspection of `domain._stack` you'll see that the stack only contains `d2`. @@ -127,8 +139,7 @@ let uid = 0; // Setting up temporary resources const buf = Buffer.alloc(FILESIZE); -for (let i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII +for (let i = 0; i < buf.length; i++) buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII fs.writeFileSync(FILENAME, buf); function ConnectionResource(c) { @@ -136,7 +147,7 @@ function ConnectionResource(c) { this._connection = c; this._alive = true; this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); + this._id = Math.random().toString(32).substr(2).substr(0, 8) + ++uid; this._domain.add(c); this._domain.on('error', () => { @@ -165,18 +176,24 @@ ConnectionResource.prototype.write = function write(chunk) { }; // Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); +net + .createServer((c) => { + const cr = new ConnectionResource(c); - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); + const d1 = domain.create(); + fs.open( + FILENAME, + 'r', + d1.intercept((fd) => { + streamInParts(fd, cr, 0); + }) + ); - pipeData(cr); + pipeData(cr); - c.on('close', () => cr.end()); -}).listen(8080); + c.on('close', () => cr.end()); + }) + .listen(8080); function streamInParts(fd, cr, pos) { const d2 = domain.create(); @@ -185,24 +202,33 @@ function streamInParts(fd, cr, pos) { print('d2 error:', er.message); cr.end(); }); - fs.read(fd, Buffer.alloc(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); + fs.read( + fd, + Buffer.alloc(10), + 0, + 10, + pos, + d2.intercept((bRead, buf) => { + if (!cr.isAlive()) { + return fs.close(fd); } - return; - } - cr.end(buf); - fs.close(fd); - })); + if (cr._connection.bytesWritten < FILESIZE) { + // Documentation says callback is optional, but doesn't mention that if + // the write fails an exception will be thrown. + const goodtogo = cr.write(buf); + if (goodtogo) { + setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); + } else { + cr._connection.once('drain', () => + streamInParts(fd, cr, pos + bRead) + ); + } + return; + } + cr.end(buf); + fs.close(fd); + }) + ); } function pipeData(cr) { @@ -244,9 +270,8 @@ process.on('exit', () => { fs.unlinkSync(pipeList[i]); } fs.unlinkSync(FILENAME); - } catch (e) { } + } catch (e) {} }); - ``` * When a new connection happens, concurrently: @@ -274,18 +299,20 @@ The following is a involved example demonstrating the failing using domains to p const domain = require('domain'); const net = require('net'); -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log('listening on 8080')); +const server = net + .createServer((c) => { + // Use a domain to propagate data across events within the + // connection so that we don't have to pass arguments + // everywhere. + const d = domain.create(); + d.data = { connection: c }; + d.add(c); + // Mock class that does some useless async data transformation + // for demonstration purposes. + const ds = new DataStream(dataTransformed); + c.on('data', (chunk) => ds.data(chunk)); + }) + .listen(8080, () => console.log('listening on 8080')); function dataTransformed(chunk) { // FAIL! Because the DataStream instance also created a diff --git a/locale/es/docs/guides/event-loop-timers-and-nexttick.md b/locale/es/docs/guides/event-loop-timers-and-nexttick.md index c1105b3a73e98..614b48914d9f3 100644 --- a/locale/es/docs/guides/event-loop-timers-and-nexttick.md +++ b/locale/es/docs/guides/event-loop-timers-and-nexttick.md @@ -207,8 +207,10 @@ Why would something like this be included in Node.js? Part of it is a design phi ```js function apiCall(arg, callback) { if (typeof arg !== 'string') - return process.nextTick(callback, - new TypeError('argument should be string')); + return process.nextTick( + callback, + new TypeError('argument should be string') + ); } ``` @@ -222,7 +224,9 @@ This philosophy can lead to some potentially problematic situations. Take this s let bar; // this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall(callback) { callback(); } +function someAsyncApiCall(callback) { + callback(); +} // the callback is called before `someAsyncApiCall` completes. someAsyncApiCall(() => { @@ -286,10 +290,10 @@ One example is to match the user's expectations. Simple example: ```js const server = net.createServer(); -server.on('connection', (conn) => { }); +server.on('connection', (conn) => {}); server.listen(8080); -server.on('listening', () => { }); +server.on('listening', () => {}); ``` Say that `listen()` is run at the beginning of the event loop, but the listening callback is placed in a `setImmediate()`. Unless a hostname is passed, binding to the port will happen immediately. For the event loop to proceed, it must hit the **poll** phase, which means there is a non-zero chance that a connection could have been received allowing the connection event to be fired before the listening event. diff --git a/locale/es/knowledge/HTTP/clients/how-to-access-query-string-parameters.md b/locale/es/knowledge/HTTP/clients/how-to-access-query-string-parameters.md index 4db8a10436167..661ab09e48b98 100644 --- a/locale/es/knowledge/HTTP/clients/how-to-access-query-string-parameters.md +++ b/locale/es/knowledge/HTTP/clients/how-to-access-query-string-parameters.md @@ -13,13 +13,15 @@ In Node.js, functionality to aid in the accessing of URL query string parameters const http = require('http'); const url = require('url'); -http.createServer(function (req, res) { - const queryObject = url.parse(req.url,true).query; - console.log(queryObject); - - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end('Feel free to add query parameters to the end of the url'); -}).listen(8080); +http + .createServer(function (req, res) { + const queryObject = url.parse(req.url, true).query; + console.log(queryObject); + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end('Feel free to add query parameters to the end of the url'); + }) + .listen(8080); ``` > To test this code run `node app.js` (app.js is name of the file) on the terminal and then go to your browser and type `http://localhost:8080/app.js?foo=bad&baz=foo` on the URL bar @@ -43,8 +45,8 @@ This method, however, must be passed just a querystring portion of a url. Passin ```js const querystring = require('querystring'); -const url = "http://example.com/index.html?code=string&key=12&id=false"; -const qs = "code=string&key=12&id=false"; +const url = 'http://example.com/index.html?code=string&key=12&id=false'; +const qs = 'code=string&key=12&id=false'; console.log(querystring.parse(qs)); // > { code: 'string', key: '12', id: 'false' } diff --git a/locale/fr/docs/guides/buffer-constructor-deprecation.md b/locale/fr/docs/guides/buffer-constructor-deprecation.md index ee1d5a8e2dd2c..2e8f906868a7f 100644 --- a/locale/fr/docs/guides/buffer-constructor-deprecation.md +++ b/locale/fr/docs/guides/buffer-constructor-deprecation.md @@ -141,7 +141,7 @@ Also, note that using TypeScript does not fix this problem for you — when libs For Node.js 0.10.x (and below) support: ```js -var buf; +let buf; if (Buffer.alloc) { buf = Buffer.alloc(number); } else { diff --git a/locale/fr/docs/guides/domain-postmortem.md b/locale/fr/docs/guides/domain-postmortem.md index 243b24a9e7603..5b26173fa7c13 100644 --- a/locale/fr/docs/guides/domain-postmortem.md +++ b/locale/fr/docs/guides/domain-postmortem.md @@ -20,7 +20,9 @@ const c = require('./c'); // module b.js const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); +d.on('error', () => { + /* silence everything */ +}); d.enter(); // module c.js @@ -40,10 +42,14 @@ const net = require('net'); const d = domain.create(); d.on('error', (err) => console.error(err.message)); -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); +d.run(() => + net + .createServer((c) => { + c.end(); + c.write('bye'); + }) + .listen(8000) +); ``` Even manually removing the connection via `d.remove(c)` does not prevent the connection's error from being automatically intercepted. @@ -57,17 +63,19 @@ const d = domain.create(); d.on('error', () => console.error('d intercepted an error')); d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); + const server = net + .createServer((c) => { + const e = domain.create(); // No 'error' handler being set. + e.run(() => { + // This will not be caught by d's error handler. + setImmediate(() => { + throw new Error('thrown from setImmediate'); + }); + // Though this one will bubble to d's error handler. + throw new Error('immediately thrown'); }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); + }) + .listen(8080); }); ``` @@ -84,21 +92,25 @@ Propagating errors across nested domains is not straight forward, if even possib ```js const d1 = domain.create(); d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); +d1.on('error', (er) => { + /* handle error */ +}); -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { +d1.run(() => + setTimeout(() => { + const d2 = domain.create(); + d2.bar = 43; + d2.on('error', (er) => console.error(er.message, domain._stack)); + d2.run(() => { setTimeout(() => { - throw new Error('outer'); + setTimeout(() => { + throw new Error('outer'); + }); + throw new Error('inner'); }); - throw new Error('inner'); }); - }); -})); + }) +); ``` Even in the case that the domain instances are being used for local storage so access to resources are made available there is still no way to allow the error to continue propagating from `d2` back to `d1`. Quick inspection may tell us that simply throwing from `d2`'s domain `'error'` handler would allow `d1` to then catch the exception and execute its own error handler. Though that is not the case. Upon inspection of `domain._stack` you'll see that the stack only contains `d2`. @@ -127,8 +139,7 @@ let uid = 0; // Setting up temporary resources const buf = Buffer.alloc(FILESIZE); -for (let i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII +for (let i = 0; i < buf.length; i++) buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII fs.writeFileSync(FILENAME, buf); function ConnectionResource(c) { @@ -136,7 +147,7 @@ function ConnectionResource(c) { this._connection = c; this._alive = true; this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); + this._id = Math.random().toString(32).substr(2).substr(0, 8) + ++uid; this._domain.add(c); this._domain.on('error', () => { @@ -165,18 +176,24 @@ ConnectionResource.prototype.write = function write(chunk) { }; // Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); +net + .createServer((c) => { + const cr = new ConnectionResource(c); - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); + const d1 = domain.create(); + fs.open( + FILENAME, + 'r', + d1.intercept((fd) => { + streamInParts(fd, cr, 0); + }) + ); - pipeData(cr); + pipeData(cr); - c.on('close', () => cr.end()); -}).listen(8080); + c.on('close', () => cr.end()); + }) + .listen(8080); function streamInParts(fd, cr, pos) { const d2 = domain.create(); @@ -185,24 +202,33 @@ function streamInParts(fd, cr, pos) { print('d2 error:', er.message); cr.end(); }); - fs.read(fd, Buffer.alloc(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); + fs.read( + fd, + Buffer.alloc(10), + 0, + 10, + pos, + d2.intercept((bRead, buf) => { + if (!cr.isAlive()) { + return fs.close(fd); } - return; - } - cr.end(buf); - fs.close(fd); - })); + if (cr._connection.bytesWritten < FILESIZE) { + // Documentation says callback is optional, but doesn't mention that if + // the write fails an exception will be thrown. + const goodtogo = cr.write(buf); + if (goodtogo) { + setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); + } else { + cr._connection.once('drain', () => + streamInParts(fd, cr, pos + bRead) + ); + } + return; + } + cr.end(buf); + fs.close(fd); + }) + ); } function pipeData(cr) { @@ -244,9 +270,8 @@ process.on('exit', () => { fs.unlinkSync(pipeList[i]); } fs.unlinkSync(FILENAME); - } catch (e) { } + } catch (e) {} }); - ``` * When a new connection happens, concurrently: @@ -274,18 +299,20 @@ The following is a involved example demonstrating the failing using domains to p const domain = require('domain'); const net = require('net'); -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log('listening on 8080')); +const server = net + .createServer((c) => { + // Use a domain to propagate data across events within the + // connection so that we don't have to pass arguments + // everywhere. + const d = domain.create(); + d.data = { connection: c }; + d.add(c); + // Mock class that does some useless async data transformation + // for demonstration purposes. + const ds = new DataStream(dataTransformed); + c.on('data', (chunk) => ds.data(chunk)); + }) + .listen(8080, () => console.log('listening on 8080')); function dataTransformed(chunk) { // FAIL! Because the DataStream instance also created a diff --git a/locale/fr/knowledge/HTTP/clients/how-to-access-query-string-parameters.md b/locale/fr/knowledge/HTTP/clients/how-to-access-query-string-parameters.md index 4db8a10436167..661ab09e48b98 100644 --- a/locale/fr/knowledge/HTTP/clients/how-to-access-query-string-parameters.md +++ b/locale/fr/knowledge/HTTP/clients/how-to-access-query-string-parameters.md @@ -13,13 +13,15 @@ In Node.js, functionality to aid in the accessing of URL query string parameters const http = require('http'); const url = require('url'); -http.createServer(function (req, res) { - const queryObject = url.parse(req.url,true).query; - console.log(queryObject); - - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end('Feel free to add query parameters to the end of the url'); -}).listen(8080); +http + .createServer(function (req, res) { + const queryObject = url.parse(req.url, true).query; + console.log(queryObject); + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end('Feel free to add query parameters to the end of the url'); + }) + .listen(8080); ``` > To test this code run `node app.js` (app.js is name of the file) on the terminal and then go to your browser and type `http://localhost:8080/app.js?foo=bad&baz=foo` on the URL bar @@ -43,8 +45,8 @@ This method, however, must be passed just a querystring portion of a url. Passin ```js const querystring = require('querystring'); -const url = "http://example.com/index.html?code=string&key=12&id=false"; -const qs = "code=string&key=12&id=false"; +const url = 'http://example.com/index.html?code=string&key=12&id=false'; +const qs = 'code=string&key=12&id=false'; console.log(querystring.parse(qs)); // > { code: 'string', key: '12', id: 'false' } diff --git a/locale/fr/knowledge/REPL/how-to-create-a-custom-repl.md b/locale/fr/knowledge/REPL/how-to-create-a-custom-repl.md index a57195f666051..caa28b2275fcf 100644 --- a/locale/fr/knowledge/REPL/how-to-create-a-custom-repl.md +++ b/locale/fr/knowledge/REPL/how-to-create-a-custom-repl.md @@ -11,7 +11,7 @@ layout: knowledge-post.hbs Node.js allows users to create their own REPLs with the [repl module](https://nodejs.org/api/repl.html). Its basic use looks like this: ```js -var repl = require('repl') +const repl = require('repl'); repl.start(prompt, stream); ``` @@ -23,26 +23,28 @@ However, the repl is pretty flexible. Here's an example that shows this off: ```js #!/usr/bin/env node -var net = require("net"); -var repl = require("repl"); +const net = require('net'); +const repl = require('repl'); -var mood = function () { - var m = [ "^__^", "-___-;", ">.<", "<_>" ]; - return m[Math.floor(Math.random()*m.length)]; +const mood = function () { + const m = ['^__^', '-___-;', '>.<', '<_>']; + return m[Math.floor(Math.random() * m.length)]; }; -//A remote node repl that you can telnet to! -net.createServer(function (socket) { - var remote = repl.start("node::remote> ", socket); - //Adding "mood" and "bonus" to the remote REPL's context. - remote.context.mood = mood; - remote.context.bonus = "UNLOCKED"; -}).listen(5001); +// A remote node repl that you can telnet to! +net + .createServer(function (socket) { + const remote = repl.start('node::remote> ', socket); + // Adding "mood" and "bonus" to the remote REPL's context. + remote.context.mood = mood; + remote.context.bonus = 'UNLOCKED'; + }) + .listen(5001); -console.log("Remote REPL started on port 5001."); +console.log('Remote REPL started on port 5001.'); -//A "local" node repl with a custom prompt -var local = repl.start("node::local> "); +// A "local" node repl with a custom prompt +const local = repl.start('node::local> '); // Exposing the function "mood" to the local REPL's context. local.context.mood = mood; diff --git a/locale/fr/knowledge/advanced/buffers/how-to-use-buffers.md b/locale/fr/knowledge/advanced/buffers/how-to-use-buffers.md index e6e56ef33cc95..e9f5e4fbddf35 100644 --- a/locale/fr/knowledge/advanced/buffers/how-to-use-buffers.md +++ b/locale/fr/knowledge/advanced/buffers/how-to-use-buffers.md @@ -34,7 +34,7 @@ In the wild, buffers are usually seen in the context of binary data coming from There are a few ways to create new buffers: ```js -var buffer = Buffer.alloc(8); +const buffer = Buffer.alloc(8); // This will print out 8 bytes of zero: // ``` @@ -42,7 +42,7 @@ var buffer = Buffer.alloc(8); This buffer is initialized and contains 8 bytes of zero. ```js -var buffer = Buffer.from([ 8, 6, 7, 5, 3, 0, 9]); +const buffer = Buffer.from([8, 6, 7, 5, 3, 0, 9]); // This will print out 8 bytes of certain values: // ``` @@ -50,7 +50,7 @@ var buffer = Buffer.from([ 8, 6, 7, 5, 3, 0, 9]); This initializes the buffer to the contents of this array. Keep in mind that the contents of the array are integers representing bytes. ```js -var buffer = Buffer.from("I'm a string!", "utf-8"); +const buffer = Buffer.from("I'm a string!", 'utf-8'); // This will print out a chain of values in utf-8: // ``` diff --git a/locale/fr/knowledge/child-processes/how-to-spawn-a-child-process.md b/locale/fr/knowledge/child-processes/how-to-spawn-a-child-process.md index 245d5d8f7479a..1658471a674b0 100644 --- a/locale/fr/knowledge/child-processes/how-to-spawn-a-child-process.md +++ b/locale/fr/knowledge/child-processes/how-to-spawn-a-child-process.md @@ -22,15 +22,15 @@ const { exec } = require('child_process'); const ls = exec('ls -l', function (error, stdout, stderr) { if (error) { console.log(error.stack); - console.log('Error code: '+error.code); - console.log('Signal received: '+error.signal); + console.log('Error code: ' + error.code); + console.log('Signal received: ' + error.signal); } - console.log('Child Process STDOUT: '+stdout); - console.log('Child Process STDERR: '+stderr); + console.log('Child Process STDOUT: ' + stdout); + console.log('Child Process STDERR: ' + stderr); }); ls.on('exit', function (code) { - console.log('Child process exited with exit code '+code); + console.log('Child process exited with exit code ' + code); }); ``` diff --git a/locale/fr/knowledge/command-line/how-to-get-colors-on-the-command-line.md b/locale/fr/knowledge/command-line/how-to-get-colors-on-the-command-line.md index eb876efc1b02b..a14a7fbf33aed 100644 --- a/locale/fr/knowledge/command-line/how-to-get-colors-on-the-command-line.md +++ b/locale/fr/knowledge/command-line/how-to-get-colors-on-the-command-line.md @@ -45,7 +45,7 @@ The last pair of `console.log` statements are probably the most important. Becau Let's look at a more explicit example. If you set the following properties with `colors.js`: ```js -myString.red.blue.green +myString.red.blue.green; ``` You can think of your terminal saying to itself, "Make this green. No, make this blue. No, make this red. No more color codes now? Red it is, then." The codes are read in the reverse order, and the last/'innermost' is applied. This can be extremely useful if you're using a library that sets its own default colors that you don't like - if you set a color code yourself on the string you pass in to the library, it will supersede the other author's color code(s). @@ -79,7 +79,7 @@ Unlike the `String.prototype` approach, the chained methods on the `colors` inst With the latest version of `colors.js` you can also define **[Custom Themes](https://www.npmjs.com/package/colors#custom-themes)** in `color.js`, which makes our code more Robust and allows better Encapsulation of data. A nice use case of this maybe: ```js -var colors = require('colors'); +const colors = require('colors'); colors.setTheme({ info: 'bgGreen', @@ -90,10 +90,10 @@ colors.setTheme({ }); // outputs red text -console.log("this is an error".error); +console.log('this is an error'.error); // outputs text on blue background -console.log("this is a success message".success); +console.log('this is a success message'.success); ``` One last thing: the colors can look quite different in different terminals - sometimes, `bold` is bold, sometimes it's just a different color. Try it out and see for yourself! diff --git a/locale/fr/knowledge/command-line/how-to-parse-command-line-arguments.md b/locale/fr/knowledge/command-line/how-to-parse-command-line-arguments.md index 611304f041062..0e439bb3e211d 100644 --- a/locale/fr/knowledge/command-line/how-to-parse-command-line-arguments.md +++ b/locale/fr/knowledge/command-line/how-to-parse-command-line-arguments.md @@ -33,7 +33,7 @@ There you have it - an array containing any arguments you passed in. Notice the Where everyday CLI arguments are concerned, you'll want to skip the first two. Now try this in `argv.js`: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); ``` @@ -47,17 +47,17 @@ myArgs: [ 'one', 'two', 'three', 'four' ] Now let's actually do something with the args: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); switch (myArgs[0]) { -case 'insult': + case 'insult': console.log(myArgs[1], 'smells quite badly.'); break; -case 'compliment': + case 'compliment': console.log(myArgs[1], 'is really cool.'); break; -default: + default: console.log('Sorry, that is not something I know how to do.'); } ``` @@ -78,33 +78,32 @@ Once you have it, give it a try - it can really be a life-saver. Lets test it wi const yargs = require('yargs'); const argv = yargs - .command('lyr', 'Tells whether an year is leap year or not', { - year: { - description: 'the year to check for', - alias: 'y', - type: 'number', - } - }) - .option('time', { - alias: 't', - description: 'Tell the present Time', - type: 'boolean', - }) - .help() - .alias('help', 'h') - .argv; + .command('lyr', 'Tells whether an year is leap year or not', { + year: { + description: 'the year to check for', + alias: 'y', + type: 'number' + } + }) + .option('time', { + alias: 't', + description: 'Tell the present Time', + type: 'boolean' + }) + .help() + .alias('help', 'h').argv; if (argv.time) { - console.log('The current time is: ', new Date().toLocaleTimeString()); + console.log('The current time is: ', new Date().toLocaleTimeString()); } if (argv._.includes('lyr')) { - const year = argv.year || new Date().getFullYear(); - if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { - console.log(`${year} is a Leap Year`); - } else { - console.log(`${year} is NOT a Leap Year`); - } + const year = argv.year || new Date().getFullYear(); + if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { + console.log(`${year} is a Leap Year`); + } else { + console.log(`${year} is NOT a Leap Year`); + } } console.log(argv); diff --git a/locale/fr/knowledge/command-line/how-to-prompt-for-command-line-input.md b/locale/fr/knowledge/command-line/how-to-prompt-for-command-line-input.md index 41d2b189fddcf..e76b67f7bcae3 100644 --- a/locale/fr/knowledge/command-line/how-to-prompt-for-command-line-input.md +++ b/locale/fr/knowledge/command-line/how-to-prompt-for-command-line-input.md @@ -16,22 +16,22 @@ Streams are the Node.js way of dealing with evented I/O - it's a big topic, and Here's a simple example. Try the following in a new file: ```js -const readline = require("readline"); +const readline = require('readline'); const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout + input: process.stdin, + output: process.stdout }); -rl.question("What is your name ? ", function(name) { - rl.question("Where do you live ? ", function(country) { - console.log(`${name}, is a citizen of ${country}`); - rl.close(); - }); +rl.question('What is your name ? ', function (name) { + rl.question('Where do you live ? ', function (country) { + console.log(`${name}, is a citizen of ${country}`); + rl.close(); + }); }); -rl.on("close", function() { - console.log("\nBYE BYE !!!"); - process.exit(0); +rl.on('close', function () { + console.log('\nBYE BYE !!!'); + process.exit(0); }); ``` @@ -57,15 +57,17 @@ const prompt = require('prompt'); prompt.start(); prompt.get(['username', 'email'], function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Email: ' + result.email); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Email: ' + result.email); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` @@ -77,29 +79,31 @@ Prompt also makes it trivial to handle a certain set of recurring properties tha const prompt = require('prompt'); const properties = [ - { - name: 'username', - validator: /^[a-zA-Z\s\-]+$/, - warning: 'Username must be only letters, spaces, or dashes' - }, - { - name: 'password', - hidden: true - } + { + name: 'username', + validator: /^[a-zA-Z\s-]+$/, + warning: 'Username must be only letters, spaces, or dashes' + }, + { + name: 'password', + hidden: true + } ]; prompt.start(); prompt.get(properties, function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Password: ' + result.password); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Password: ' + result.password); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` diff --git a/locale/fr/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md b/locale/fr/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md index d783fcff77283..2eb4f0f6dc082 100644 --- a/locale/fr/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md +++ b/locale/fr/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md @@ -13,10 +13,10 @@ Usually a function will take a set number of parameters, and require that all of ```js const pow = (base, power = 2) => { return Math.pow(base, power); -} +}; console.log(pow(2)); // 4 -console.log(pow(2,10)); // 1024 +console.log(pow(2, 10)); // 1024 ``` In the above code The function `pow` return square of a number or any other power specified in the function call because the argument `power` is given a default value of 2 so whenever no second argument is provided or the provided value is `undefined` the function `pow` will use 2 as the value of argument `power`. But there is a small gotcha in it: @@ -24,7 +24,7 @@ In the above code The function `pow` return square of a number or any other powe ```js const pow = (base, power = 2) => { return Math.pow(base, power); -} +}; console.log(pow(2, undefined)); // 4 console.log(pow(2, null)); // 1 @@ -40,28 +40,28 @@ The first idiom is giving a default value for the last parameter. This is done b ```js const example = function (optionalArg) { - optionalArg = optionalArg || "No parameter was passed"; + optionalArg = optionalArg || 'No parameter was passed'; console.log(optionalArg); -} +}; const betterExample = function (optionalArg) { if (optionalArg === undefined) { - optionalArg = "No parameter was passed"; + optionalArg = 'No parameter was passed'; } console.log(optionalArg); -} +}; -console.log("Without parameter:"); +console.log('Without parameter:'); example(); betterExample(); -console.log("\nWith paramater:"); -example("parameter was passed"); -betterExample("parameter was passed"); +console.log('\nWith paramater:'); +example('parameter was passed'); +betterExample('parameter was passed'); -console.log("\nEmpty String:"); -example(""); -betterExample(""); +console.log('\nEmpty String:'); +example(''); +betterExample(''); ``` The second idiom is when the optional value is in the middle it can cause some undesired effects since all the parameters are shifted over. The optional parameter is not the `undefined` value in this case - the last parameter is the `undefined` one. So you have to check if the last parameter is `undefined` and then manually fix all the other parameters before continuing in the code. This case is also valid for modern JavaScript(ES6/ES2015). The example shows you how to do that: @@ -72,12 +72,16 @@ const example = function (param1, optParam, callback) { // only two parameters were passed, so the callback is actually in `optParam` callback = optParam; - //give `optParam` a default value - optParam = "and a default parameter"; + // give `optParam` a default value + optParam = 'and a default parameter'; } callback(param1, optParam); -} - -example("This is a necessary parameter", console.log); -example("This is a necessary parameter", "and an optional parameter", console.log); +}; + +example('This is a necessary parameter', console.log); +example( + 'This is a necessary parameter', + 'and an optional parameter', + console.log +); ``` diff --git a/locale/fr/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md b/locale/fr/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md index 52e993be22934..e5f1d7142bce5 100644 --- a/locale/fr/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md +++ b/locale/fr/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md @@ -12,8 +12,12 @@ layout: knowledge-post.hbs There are two most common built-in timer functions, `setTimeout` and `setInterval`, which can be used to call a function at a later time. For an example usage: ```js -setTimeout(function() { console.log("setTimeout: It's been one second!"); }, 1000); -setInterval(function() { console.log("setInterval: It's been one second!"); }, 1000); +setTimeout(function () { + console.log("setTimeout: It's been one second!"); +}, 1000); +setInterval(function () { + console.log("setInterval: It's been one second!"); +}, 1000); ``` An example output is: @@ -39,9 +43,9 @@ This can cause problems, however, if your server is slow and it takes, for examp ```js const recursive = function () { - console.log("It has been one second!"); - setTimeout(recursive,1000); -} + console.log('It has been one second!'); + setTimeout(recursive, 1000); +}; recursive(); ``` @@ -50,12 +54,12 @@ As you can see, it makes a call to the `recursive` function which, as it complet You can clear the timers you set with `clearTimeout` and `clearInterval`. Their usages are very simple: ```js -function never_call () { - console.log("You should never call this function"); +function neverCall() { + console.log('You should never call this function'); } -const id1 = setTimeout(never_call,1000); -const id2 = setInterval(never_call,1000); +const id1 = setTimeout(neverCall, 1000); +const id2 = setInterval(neverCall, 1000); clearTimeout(id1); clearInterval(id2); @@ -66,8 +70,8 @@ So if you keep track of the return values of the timers, you can easily unhook t The final trick for the timer objects is you can pass parameters to the callback by passing more parameters to setTimeout and setInterval: ```js -setTimeout(console.log, 1000, "This", "has", 4, "parameters"); -setInterval(console.log, 1000, "This only has one"); +setTimeout(console.log, 1000, 'This', 'has', 4, 'parameters'); +setInterval(console.log, 1000, 'This only has one'); ``` The output is: @@ -87,9 +91,9 @@ This only has one `setImmediate()` is another built-in timer function which as the name suggest, runs immediately after the first iteration of the event loop is completed. In other words, `setImmediate()` is similar to a `setTimeout()` function with a `0ms` delay. The `setImmediate()` function can also take extra parameters that are passed when the callback is called: ```js -console.log("This will be printed first"); -setImmediate(console.log, "This is an extra parameter"); -console.log("This will be printed second"); +console.log('This will be printed first'); +setImmediate(console.log, 'This is an extra parameter'); +console.log('This will be printed second'); ``` The output is: diff --git a/locale/fr/knowledge/javascript-conventions/what-is-json.md b/locale/fr/knowledge/javascript-conventions/what-is-json.md index 998cf3ec042a2..64fb8f5c59c52 100644 --- a/locale/fr/knowledge/javascript-conventions/what-is-json.md +++ b/locale/fr/knowledge/javascript-conventions/what-is-json.md @@ -27,10 +27,10 @@ JavaScript provides 2 methods for encoding data structures to json and encoding ```js const data = { - name: "John Doe", + name: 'John Doe', age: 32, - title: "Vice President of JavaScript" -} + title: 'Vice President of JavaScript' +}; const jsonStr = JSON.stringify(data); @@ -42,7 +42,8 @@ console.log(jsonStr); `JSON.parse` takes a JSON string and decodes it to a JavaScript data structure. ```js -const jsonStr = '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'; +const jsonStr = + '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'; const data = JSON.parse(jsonStr); diff --git a/locale/fr/knowledge/javascript-conventions/what-is-the-arguments-object.md b/locale/fr/knowledge/javascript-conventions/what-is-the-arguments-object.md index dc85f2e98bed5..c81a314370f7d 100644 --- a/locale/fr/knowledge/javascript-conventions/what-is-the-arguments-object.md +++ b/locale/fr/knowledge/javascript-conventions/what-is-the-arguments-object.md @@ -15,11 +15,11 @@ The `arguments` object is a special construct available inside all function call The `arguments` object is an array-like object. It has a length property that corresponds to the number of arguments passed into the function. You can access these values by indexing into the array, e.g. `arguments[0]` is the first argument. The only other property of `arguments` is callee, which ES5 forbids to use in `strict mode` more about it could be found [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee). Here's an example that illustrates the properties of `arguments`. ```js -const myfunc = function(one) { +const myfunc = function (one) { arguments[0] === one; arguments[1] === 2; arguments.length === 3; -} +}; myfunc(1, 2, 3); ``` @@ -27,10 +27,10 @@ myfunc(1, 2, 3); This construct is very useful and gives JavaScript functions a lot of flexibility. But there is an important gotcha. The `arguments` object behaves like an array, but it is not an actual array. It does not have Array in its prototype chain and it does not respond to any array methods, e.g. `arguments.sort()` raises a TypeError. Instead, you need to copy the values into a true array first. With the advent of ES6 `Array.from()` method this is quite straightforward. ```js -const myfunc = function(a, b, c) { +const myfunc = function (a, b, c) { const args = Array.from(arguments); - console.log(args) // [1, 2, 3] -} + console.log(args); // [1, 2, 3] +}; myfunc(1, 2, 3); ``` @@ -40,10 +40,10 @@ NOTE: For ES5 and below, a normal `for` loop can do the trick. In certain cases you can still treat `arguments` as an array. You can use `arguments` in dynamic function invocations using apply. And most native Array methods will also accept `arguments` when dynamically invoked using call or apply. This technique also suggests another way to convert `arguments` into a true array using the `Array.slice` method. ```js -myfunc.apply(obj, arguments). - -// concat arguments onto the -Array.prototype.concat.apply([1,2,3], arguments); +myfunc + .apply(obj, arguments) + // concat arguments onto the + .Array.prototype.concat.apply([1, 2, 3], arguments); // turn arguments into a true array const args = Array.prototype.slice.call(arguments); @@ -59,7 +59,7 @@ The `arrow functions` were added in the ECMAScript 2015 (ES6) specification as a ```js const myfunc = (...args) => { console.log('first parameter is ', args[0]); -} +}; myfunc(1, 2, 3); ``` diff --git a/locale/ja/docs/guides/buffer-constructor-deprecation.md b/locale/ja/docs/guides/buffer-constructor-deprecation.md index 8bc9cb948f03c..6f8fc0ee9f483 100644 --- a/locale/ja/docs/guides/buffer-constructor-deprecation.md +++ b/locale/ja/docs/guides/buffer-constructor-deprecation.md @@ -278,7 +278,7 @@ TS がコンパイルする実際の JS コードには存在しません。 Node.js 0.10.x (およびそれ以下) をサポートする場合 ```js -var buf; +let buf; if (Buffer.alloc) { buf = Buffer.alloc(number); } else { diff --git a/locale/ko/docs/guides/domain-postmortem.md b/locale/ko/docs/guides/domain-postmortem.md index f064f0a600d70..b88cea954dfd2 100644 --- a/locale/ko/docs/guides/domain-postmortem.md +++ b/locale/ko/docs/guides/domain-postmortem.md @@ -63,7 +63,9 @@ const c = require('./c'); // 모듈 b.js const d = require('domain').create(); -d.on('error', () => { /* 모든 것을 무시합니다. */ }); +d.on('error', () => { + /* 모든 것을 무시합니다. */ +}); d.enter(); // 모듈 c.js @@ -117,10 +119,14 @@ const net = require('net'); const d = domain.create(); d.on('error', (err) => console.error(err.message)); -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); +d.run(() => + net + .createServer((c) => { + c.end(); + c.write('bye'); + }) + .listen(8000) +); ``` Primeiro instale-o no diretório ao qual você gostaria de trabalhar. -```js +```shell cd mydir npm install colors ``` @@ -21,22 +21,22 @@ npm install colors Agora faça um pequeno _script_ de teste. Tente algo assim: ```js -const colors = require('colors') +const colors = require('colors'); -const stringOne = 'This is a plain string.' -const stringTwo = 'This string is red.'.red -const stringThree = 'This string is blue.'.blue -const today = new Date().toLocaleDateString() // retorna a data de hoje no formato mm/dd/yyyy +const stringOne = 'This is a plain string.'; +const stringTwo = 'This string is red.'.red; +const stringThree = 'This string is blue.'.blue; +const today = new Date().toLocaleDateString(); // retorna a data de hoje no formato mm/dd/yyyy -console.log(stringOne.black.bgMagenta) -console.log(stringOne.yellow.bgRed.bold) -console.log(`Today is: ${today}`.black.bgGreen) +console.log(stringOne.black.bgMagenta); +console.log(stringOne.yellow.bgRed.bold); +console.log(`Today is: ${today}`.black.bgGreen); -console.log(stringTwo) -console.log(stringThree) +console.log(stringTwo); +console.log(stringThree); -console.log(stringTwo.magenta) -console.log(stringThree.grey.bold) +console.log(stringTwo.magenta); +console.log(stringThree.grey.bold); ``` @@ -52,7 +52,7 @@ O último par de chamadas `console.log` é, provavelmente, o mais importante. Po Vamos dar uma olhada em um exemplo mais explícito. Se você você passar as seguintes propriedades com `colors.js`: ```js -myString.red.blue.green +myString.red.blue.green; ``` @@ -67,22 +67,22 @@ Now an instance of `colors` can also be used. Though this approach is slightly l Agora uma instânia de `colors` também pode ser usada. Embora esta abordagem seja menos engenhosa, é amigável à iniciantes e é especialmente útil se você não deseja alterar `String.prototype`. Alguns exemplos disto são: ```js -const colors = require('colors') +const colors = require('colors'); -const stringOne = 'This is a plain string.' -const stringTwo = 'This string is red.' -const stringThree = 'This string is blue.' -const today = new Date().toLocaleDateString() // retorna a data de hoje no formato mm/dd/yyyy +const stringOne = 'This is a plain string.'; +const stringTwo = 'This string is red.'; +const stringThree = 'This string is blue.'; +const today = new Date().toLocaleDateString(); // retorna a data de hoje no formato mm/dd/yyyy -console.log(colors.bgMagenta.black(stringOne)) -console.log(colors.bold.bgRed.yellow(stringOne)) -console.log(colors.bgGreen.black(`Today is: ${today}`)) +console.log(colors.bgMagenta.black(stringOne)); +console.log(colors.bold.bgRed.yellow(stringOne)); +console.log(colors.bgGreen.black(`Today is: ${today}`)); -console.log(colors.red(stringTwo)) -console.log(colors.blue(stringThree)) +console.log(colors.red(stringTwo)); +console.log(colors.blue(stringThree)); -console.log(colors.magenta.red(stringTwo)) -console.log(colors.bold.grey.black.blue(stringThree)) +console.log(colors.magenta.red(stringTwo)); +console.log(colors.bold.grey.black.blue(stringThree)); ``` @@ -92,7 +92,7 @@ console.log(colors.bold.grey.black.blue(stringThree)) Com a última versão de `colors.js` você pode definir **[Temas Personalizados](https://www.npmjs.com/package/colors#custom-themes)** no colors.js o que faz com que seu código seja mais robusto e permite melhor encapsulamento de dados. Um bom exemplo de caso de uso pode ser: ```js -var colors = require('colors') +const colors = require('colors'); colors.setTheme({ info: 'bgGreen', @@ -100,13 +100,13 @@ colors.setTheme({ warn: 'yellow', success: 'bgBlue', error: 'red' -}) +}); // imprime texto em vermelho -console.log('this is an error'.error) +console.log('this is an error'.error); // imprime texto com fundo azul -console.log('this is a success message'.success) +console.log('this is a success message'.success); ``` diff --git a/locale/pt-br/knowledge/command-line/how-to-parse-command-line-arguments.md b/locale/pt-br/knowledge/command-line/how-to-parse-command-line-arguments.md index 70685fc244b10..1b60d2c1ca7e2 100644 --- a/locale/pt-br/knowledge/command-line/how-to-parse-command-line-arguments.md +++ b/locale/pt-br/knowledge/command-line/how-to-parse-command-line-arguments.md @@ -43,7 +43,7 @@ Pronto - agora você tem um array contendo os argumentos que passou. Perceba os No que diz respeito a uso de argumentos no dia-a-dia, você provavelmente vai querer pular os dois primeiros. Agora tente isso em `argv.js`: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); ``` @@ -61,17 +61,17 @@ myArgs: [ 'one', 'two', 'three', 'four' ] Agora vamos tentar fazer algo diferente com os argumentos: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); switch (myArgs[0]) { -case 'insult': + case 'insult': console.log(myArgs[1], 'smells quite badly.'); break; -case 'compliment': + case 'compliment': console.log(myArgs[1], 'is really cool.'); break; -default: + default: console.log('Sorry, that is not something I know how to do.'); } ``` @@ -99,33 +99,32 @@ Assim que instalar, faça uns testes - pode ser de grande ajuda. Vamos testar co const yargs = require('yargs'); const argv = yargs - .command('lyr', 'Tells whether an year is leap year or not', { - year: { - description: 'the year to check for', - alias: 'y', - type: 'number', - } - }) - .option('time', { - alias: 't', - description: 'Tell the present Time', - type: 'boolean', - }) - .help() - .alias('help', 'h') - .argv; + .command('lyr', 'Tells whether an year is leap year or not', { + year: { + description: 'the year to check for', + alias: 'y', + type: 'number' + } + }) + .option('time', { + alias: 't', + description: 'Tell the present Time', + type: 'boolean' + }) + .help() + .alias('help', 'h').argv; if (argv.time) { - console.log('The current time is: ', new Date().toLocaleTimeString()); + console.log('The current time is: ', new Date().toLocaleTimeString()); } if (argv._.includes('lyr')) { - const year = argv.year || new Date().getFullYear(); - if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { - console.log(`${year} is a Leap Year`); - } else { - console.log(`${year} is NOT a Leap Year`); - } + const year = argv.year || new Date().getFullYear(); + if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { + console.log(`${year} is a Leap Year`); + } else { + console.log(`${year} is NOT a Leap Year`); + } } console.log(argv); diff --git a/locale/pt-br/knowledge/command-line/how-to-prompt-for-command-line-input.md b/locale/pt-br/knowledge/command-line/how-to-prompt-for-command-line-input.md index 942669baef03b..e17b4ce237f90 100644 --- a/locale/pt-br/knowledge/command-line/how-to-prompt-for-command-line-input.md +++ b/locale/pt-br/knowledge/command-line/how-to-prompt-for-command-line-input.md @@ -22,22 +22,22 @@ Streams são a forma do Node.js lidar com tipos de E/S - é um tópico important Segue um exemplo simples. Tente o seguinte um novo arquivo: ```js -const readline = require("readline"); +const readline = require('readline'); const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout + input: process.stdin, + output: process.stdout }); -rl.question("What is your name ? ", function(name) { - rl.question("Where do you live ? ", function(country) { - console.log(`${name}, is a citizen of ${country}`); - rl.close(); - }); +rl.question('What is your name ? ', function (name) { + rl.question('Where do you live ? ', function (country) { + console.log(`${name}, is a citizen of ${country}`); + rl.close(); + }); }); -rl.on("close", function() { - console.log("\nBYE BYE !!!"); - process.exit(0); +rl.on('close', function () { + console.log('\nBYE BYE !!!'); + process.exit(0); }); ``` @@ -76,15 +76,17 @@ const prompt = require('prompt'); prompt.start(); prompt.get(['username', 'email'], function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Email: ' + result.email); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Email: ' + result.email); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` @@ -100,29 +102,31 @@ Usar o prompt também torna trivial lidar com um determinado conjunto de proprie const prompt = require('prompt'); const properties = [ - { - name: 'username', - validator: /^[a-zA-Z\s\-]+$/, - warning: 'Username must be only letters, spaces, or dashes' - }, - { - name: 'password', - hidden: true - } + { + name: 'username', + validator: /^[a-zA-Z\s-]+$/, + warning: 'Username must be only letters, spaces, or dashes' + }, + { + name: 'password', + hidden: true + } ]; prompt.start(); prompt.get(properties, function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Password: ' + result.password); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Password: ' + result.password); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` diff --git a/locale/pt-br/knowledge/javascript-conventions/what-is-json.md b/locale/pt-br/knowledge/javascript-conventions/what-is-json.md index 8293e1b006fb5..c20ad247b268a 100644 --- a/locale/pt-br/knowledge/javascript-conventions/what-is-json.md +++ b/locale/pt-br/knowledge/javascript-conventions/what-is-json.md @@ -34,9 +34,9 @@ serializada no formato JSON. ```js const dados = { - nome: "John Doe", + nome: 'John Doe', idade: 32, - titulo: "Vice Presidente do JavaScript" + titulo: 'Vice Presidente do JavaScript' }; const jsonStr = JSON.stringify(dados); diff --git a/locale/pt-br/knowledge/javascript-conventions/what-is-the-arguments-object.md b/locale/pt-br/knowledge/javascript-conventions/what-is-the-arguments-object.md index ab0873c005630..d7e75a8a64be6 100644 --- a/locale/pt-br/knowledge/javascript-conventions/what-is-the-arguments-object.md +++ b/locale/pt-br/knowledge/javascript-conventions/what-is-the-arguments-object.md @@ -16,11 +16,11 @@ O objeto `arguments` é um array-like, seu tamanho corresponde a quantidade de a Veja mais exemplos sobre as propriedades de `arguments`. ```js -const myfunc = function(one) { +const myfunc = function (one) { arguments[0] === one; arguments[1] === 2; arguments.length === 3; -} +}; myfunc(1, 2, 3); ``` @@ -29,10 +29,10 @@ Essa construção é muito útil e fornece muitas funções ao JavaScript. Mas h Com o advento do ES6 o método `Array.from()` torna isso bastante simples. ```js -const myfunc = function(a, b, c) { +const myfunc = function (a, b, c) { const args = Array.from(arguments); - console.log(args) // [1, 2, 3] -} + console.log(args); // [1, 2, 3] +}; myfunc(1, 2, 3); ``` @@ -42,10 +42,10 @@ NOTA: Para ES5 e anteriores, um loop `for` normal pode fazer o truque Em alguns casos você ainda pode tratar o `arguments` como um Array, você pode usar o `arguments` através de invocações de funções dinâmicas. E a maioria dos métodos nativos Array (Ex. Array.prototype.concat) aceitarão `arguments` quando invocados dinamicamente utilizando `call` ou `apply`. Essa técnica também oferece outros modos de conversão dos `arguments` para um tipo Array utilizando método `Array.slice`. ```js -myfunc.apply(obj, arguments). - -// concat arguments onto the -Array.prototype.concat.apply([1,2,3], arguments); +myfunc + .apply(obj, arguments) + // concat arguments onto the + .Array.prototype.concat.apply([1, 2, 3], arguments); // turn arguments into a true array const args = Array.prototype.slice.call(arguments); @@ -61,7 +61,7 @@ As `arrow functions` foram adicionadas na especificação do ECMAScript 2015 (ES ```js const myfunc = (...args) => { console.log('first parameter is ', args[0]); -} +}; myfunc(1, 2, 3); ``` diff --git a/locale/ro/docs/guides/buffer-constructor-deprecation.md b/locale/ro/docs/guides/buffer-constructor-deprecation.md index ee1d5a8e2dd2c..2e8f906868a7f 100644 --- a/locale/ro/docs/guides/buffer-constructor-deprecation.md +++ b/locale/ro/docs/guides/buffer-constructor-deprecation.md @@ -141,7 +141,7 @@ Also, note that using TypeScript does not fix this problem for you — when libs For Node.js 0.10.x (and below) support: ```js -var buf; +let buf; if (Buffer.alloc) { buf = Buffer.alloc(number); } else { diff --git a/locale/ro/docs/guides/domain-postmortem.md b/locale/ro/docs/guides/domain-postmortem.md index 243b24a9e7603..5b26173fa7c13 100644 --- a/locale/ro/docs/guides/domain-postmortem.md +++ b/locale/ro/docs/guides/domain-postmortem.md @@ -20,7 +20,9 @@ const c = require('./c'); // module b.js const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); +d.on('error', () => { + /* silence everything */ +}); d.enter(); // module c.js @@ -40,10 +42,14 @@ const net = require('net'); const d = domain.create(); d.on('error', (err) => console.error(err.message)); -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); +d.run(() => + net + .createServer((c) => { + c.end(); + c.write('bye'); + }) + .listen(8000) +); ``` Even manually removing the connection via `d.remove(c)` does not prevent the connection's error from being automatically intercepted. @@ -57,17 +63,19 @@ const d = domain.create(); d.on('error', () => console.error('d intercepted an error')); d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); + const server = net + .createServer((c) => { + const e = domain.create(); // No 'error' handler being set. + e.run(() => { + // This will not be caught by d's error handler. + setImmediate(() => { + throw new Error('thrown from setImmediate'); + }); + // Though this one will bubble to d's error handler. + throw new Error('immediately thrown'); }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); + }) + .listen(8080); }); ``` @@ -84,21 +92,25 @@ Propagating errors across nested domains is not straight forward, if even possib ```js const d1 = domain.create(); d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); +d1.on('error', (er) => { + /* handle error */ +}); -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { +d1.run(() => + setTimeout(() => { + const d2 = domain.create(); + d2.bar = 43; + d2.on('error', (er) => console.error(er.message, domain._stack)); + d2.run(() => { setTimeout(() => { - throw new Error('outer'); + setTimeout(() => { + throw new Error('outer'); + }); + throw new Error('inner'); }); - throw new Error('inner'); }); - }); -})); + }) +); ``` Even in the case that the domain instances are being used for local storage so access to resources are made available there is still no way to allow the error to continue propagating from `d2` back to `d1`. Quick inspection may tell us that simply throwing from `d2`'s domain `'error'` handler would allow `d1` to then catch the exception and execute its own error handler. Though that is not the case. Upon inspection of `domain._stack` you'll see that the stack only contains `d2`. @@ -127,8 +139,7 @@ let uid = 0; // Setting up temporary resources const buf = Buffer.alloc(FILESIZE); -for (let i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII +for (let i = 0; i < buf.length; i++) buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII fs.writeFileSync(FILENAME, buf); function ConnectionResource(c) { @@ -136,7 +147,7 @@ function ConnectionResource(c) { this._connection = c; this._alive = true; this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); + this._id = Math.random().toString(32).substr(2).substr(0, 8) + ++uid; this._domain.add(c); this._domain.on('error', () => { @@ -165,18 +176,24 @@ ConnectionResource.prototype.write = function write(chunk) { }; // Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); +net + .createServer((c) => { + const cr = new ConnectionResource(c); - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); + const d1 = domain.create(); + fs.open( + FILENAME, + 'r', + d1.intercept((fd) => { + streamInParts(fd, cr, 0); + }) + ); - pipeData(cr); + pipeData(cr); - c.on('close', () => cr.end()); -}).listen(8080); + c.on('close', () => cr.end()); + }) + .listen(8080); function streamInParts(fd, cr, pos) { const d2 = domain.create(); @@ -185,24 +202,33 @@ function streamInParts(fd, cr, pos) { print('d2 error:', er.message); cr.end(); }); - fs.read(fd, Buffer.alloc(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); + fs.read( + fd, + Buffer.alloc(10), + 0, + 10, + pos, + d2.intercept((bRead, buf) => { + if (!cr.isAlive()) { + return fs.close(fd); } - return; - } - cr.end(buf); - fs.close(fd); - })); + if (cr._connection.bytesWritten < FILESIZE) { + // Documentation says callback is optional, but doesn't mention that if + // the write fails an exception will be thrown. + const goodtogo = cr.write(buf); + if (goodtogo) { + setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); + } else { + cr._connection.once('drain', () => + streamInParts(fd, cr, pos + bRead) + ); + } + return; + } + cr.end(buf); + fs.close(fd); + }) + ); } function pipeData(cr) { @@ -244,9 +270,8 @@ process.on('exit', () => { fs.unlinkSync(pipeList[i]); } fs.unlinkSync(FILENAME); - } catch (e) { } + } catch (e) {} }); - ``` * When a new connection happens, concurrently: @@ -274,18 +299,20 @@ The following is a involved example demonstrating the failing using domains to p const domain = require('domain'); const net = require('net'); -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log('listening on 8080')); +const server = net + .createServer((c) => { + // Use a domain to propagate data across events within the + // connection so that we don't have to pass arguments + // everywhere. + const d = domain.create(); + d.data = { connection: c }; + d.add(c); + // Mock class that does some useless async data transformation + // for demonstration purposes. + const ds = new DataStream(dataTransformed); + c.on('data', (chunk) => ds.data(chunk)); + }) + .listen(8080, () => console.log('listening on 8080')); function dataTransformed(chunk) { // FAIL! Because the DataStream instance also created a diff --git a/locale/ro/docs/guides/event-loop-timers-and-nexttick.md b/locale/ro/docs/guides/event-loop-timers-and-nexttick.md index c1105b3a73e98..614b48914d9f3 100644 --- a/locale/ro/docs/guides/event-loop-timers-and-nexttick.md +++ b/locale/ro/docs/guides/event-loop-timers-and-nexttick.md @@ -207,8 +207,10 @@ Why would something like this be included in Node.js? Part of it is a design phi ```js function apiCall(arg, callback) { if (typeof arg !== 'string') - return process.nextTick(callback, - new TypeError('argument should be string')); + return process.nextTick( + callback, + new TypeError('argument should be string') + ); } ``` @@ -222,7 +224,9 @@ This philosophy can lead to some potentially problematic situations. Take this s let bar; // this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall(callback) { callback(); } +function someAsyncApiCall(callback) { + callback(); +} // the callback is called before `someAsyncApiCall` completes. someAsyncApiCall(() => { @@ -286,10 +290,10 @@ One example is to match the user's expectations. Simple example: ```js const server = net.createServer(); -server.on('connection', (conn) => { }); +server.on('connection', (conn) => {}); server.listen(8080); -server.on('listening', () => { }); +server.on('listening', () => {}); ``` Say that `listen()` is run at the beginning of the event loop, but the listening callback is placed in a `setImmediate()`. Unless a hostname is passed, binding to the port will happen immediately. For the event loop to proceed, it must hit the **poll** phase, which means there is a non-zero chance that a connection could have been received allowing the connection event to be fired before the listening event. diff --git a/locale/ro/knowledge/HTTP/clients/how-to-access-query-string-parameters.md b/locale/ro/knowledge/HTTP/clients/how-to-access-query-string-parameters.md index 4db8a10436167..661ab09e48b98 100644 --- a/locale/ro/knowledge/HTTP/clients/how-to-access-query-string-parameters.md +++ b/locale/ro/knowledge/HTTP/clients/how-to-access-query-string-parameters.md @@ -13,13 +13,15 @@ In Node.js, functionality to aid in the accessing of URL query string parameters const http = require('http'); const url = require('url'); -http.createServer(function (req, res) { - const queryObject = url.parse(req.url,true).query; - console.log(queryObject); - - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end('Feel free to add query parameters to the end of the url'); -}).listen(8080); +http + .createServer(function (req, res) { + const queryObject = url.parse(req.url, true).query; + console.log(queryObject); + + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end('Feel free to add query parameters to the end of the url'); + }) + .listen(8080); ``` > To test this code run `node app.js` (app.js is name of the file) on the terminal and then go to your browser and type `http://localhost:8080/app.js?foo=bad&baz=foo` on the URL bar @@ -43,8 +45,8 @@ This method, however, must be passed just a querystring portion of a url. Passin ```js const querystring = require('querystring'); -const url = "http://example.com/index.html?code=string&key=12&id=false"; -const qs = "code=string&key=12&id=false"; +const url = 'http://example.com/index.html?code=string&key=12&id=false'; +const qs = 'code=string&key=12&id=false'; console.log(querystring.parse(qs)); // > { code: 'string', key: '12', id: 'false' } diff --git a/locale/ro/knowledge/REPL/how-to-create-a-custom-repl.md b/locale/ro/knowledge/REPL/how-to-create-a-custom-repl.md index a57195f666051..caa28b2275fcf 100644 --- a/locale/ro/knowledge/REPL/how-to-create-a-custom-repl.md +++ b/locale/ro/knowledge/REPL/how-to-create-a-custom-repl.md @@ -11,7 +11,7 @@ layout: knowledge-post.hbs Node.js allows users to create their own REPLs with the [repl module](https://nodejs.org/api/repl.html). Its basic use looks like this: ```js -var repl = require('repl') +const repl = require('repl'); repl.start(prompt, stream); ``` @@ -23,26 +23,28 @@ However, the repl is pretty flexible. Here's an example that shows this off: ```js #!/usr/bin/env node -var net = require("net"); -var repl = require("repl"); +const net = require('net'); +const repl = require('repl'); -var mood = function () { - var m = [ "^__^", "-___-;", ">.<", "<_>" ]; - return m[Math.floor(Math.random()*m.length)]; +const mood = function () { + const m = ['^__^', '-___-;', '>.<', '<_>']; + return m[Math.floor(Math.random() * m.length)]; }; -//A remote node repl that you can telnet to! -net.createServer(function (socket) { - var remote = repl.start("node::remote> ", socket); - //Adding "mood" and "bonus" to the remote REPL's context. - remote.context.mood = mood; - remote.context.bonus = "UNLOCKED"; -}).listen(5001); +// A remote node repl that you can telnet to! +net + .createServer(function (socket) { + const remote = repl.start('node::remote> ', socket); + // Adding "mood" and "bonus" to the remote REPL's context. + remote.context.mood = mood; + remote.context.bonus = 'UNLOCKED'; + }) + .listen(5001); -console.log("Remote REPL started on port 5001."); +console.log('Remote REPL started on port 5001.'); -//A "local" node repl with a custom prompt -var local = repl.start("node::local> "); +// A "local" node repl with a custom prompt +const local = repl.start('node::local> '); // Exposing the function "mood" to the local REPL's context. local.context.mood = mood; diff --git a/locale/ro/knowledge/advanced/buffers/how-to-use-buffers.md b/locale/ro/knowledge/advanced/buffers/how-to-use-buffers.md index e6e56ef33cc95..e9f5e4fbddf35 100644 --- a/locale/ro/knowledge/advanced/buffers/how-to-use-buffers.md +++ b/locale/ro/knowledge/advanced/buffers/how-to-use-buffers.md @@ -34,7 +34,7 @@ In the wild, buffers are usually seen in the context of binary data coming from There are a few ways to create new buffers: ```js -var buffer = Buffer.alloc(8); +const buffer = Buffer.alloc(8); // This will print out 8 bytes of zero: // ``` @@ -42,7 +42,7 @@ var buffer = Buffer.alloc(8); This buffer is initialized and contains 8 bytes of zero. ```js -var buffer = Buffer.from([ 8, 6, 7, 5, 3, 0, 9]); +const buffer = Buffer.from([8, 6, 7, 5, 3, 0, 9]); // This will print out 8 bytes of certain values: // ``` @@ -50,7 +50,7 @@ var buffer = Buffer.from([ 8, 6, 7, 5, 3, 0, 9]); This initializes the buffer to the contents of this array. Keep in mind that the contents of the array are integers representing bytes. ```js -var buffer = Buffer.from("I'm a string!", "utf-8"); +const buffer = Buffer.from("I'm a string!", 'utf-8'); // This will print out a chain of values in utf-8: // ``` diff --git a/locale/ro/knowledge/child-processes/how-to-spawn-a-child-process.md b/locale/ro/knowledge/child-processes/how-to-spawn-a-child-process.md index 245d5d8f7479a..1658471a674b0 100644 --- a/locale/ro/knowledge/child-processes/how-to-spawn-a-child-process.md +++ b/locale/ro/knowledge/child-processes/how-to-spawn-a-child-process.md @@ -22,15 +22,15 @@ const { exec } = require('child_process'); const ls = exec('ls -l', function (error, stdout, stderr) { if (error) { console.log(error.stack); - console.log('Error code: '+error.code); - console.log('Signal received: '+error.signal); + console.log('Error code: ' + error.code); + console.log('Signal received: ' + error.signal); } - console.log('Child Process STDOUT: '+stdout); - console.log('Child Process STDERR: '+stderr); + console.log('Child Process STDOUT: ' + stdout); + console.log('Child Process STDERR: ' + stderr); }); ls.on('exit', function (code) { - console.log('Child process exited with exit code '+code); + console.log('Child process exited with exit code ' + code); }); ``` diff --git a/locale/ro/knowledge/command-line/how-to-get-colors-on-the-command-line.md b/locale/ro/knowledge/command-line/how-to-get-colors-on-the-command-line.md index eb876efc1b02b..a14a7fbf33aed 100644 --- a/locale/ro/knowledge/command-line/how-to-get-colors-on-the-command-line.md +++ b/locale/ro/knowledge/command-line/how-to-get-colors-on-the-command-line.md @@ -45,7 +45,7 @@ The last pair of `console.log` statements are probably the most important. Becau Let's look at a more explicit example. If you set the following properties with `colors.js`: ```js -myString.red.blue.green +myString.red.blue.green; ``` You can think of your terminal saying to itself, "Make this green. No, make this blue. No, make this red. No more color codes now? Red it is, then." The codes are read in the reverse order, and the last/'innermost' is applied. This can be extremely useful if you're using a library that sets its own default colors that you don't like - if you set a color code yourself on the string you pass in to the library, it will supersede the other author's color code(s). @@ -79,7 +79,7 @@ Unlike the `String.prototype` approach, the chained methods on the `colors` inst With the latest version of `colors.js` you can also define **[Custom Themes](https://www.npmjs.com/package/colors#custom-themes)** in `color.js`, which makes our code more Robust and allows better Encapsulation of data. A nice use case of this maybe: ```js -var colors = require('colors'); +const colors = require('colors'); colors.setTheme({ info: 'bgGreen', @@ -90,10 +90,10 @@ colors.setTheme({ }); // outputs red text -console.log("this is an error".error); +console.log('this is an error'.error); // outputs text on blue background -console.log("this is a success message".success); +console.log('this is a success message'.success); ``` One last thing: the colors can look quite different in different terminals - sometimes, `bold` is bold, sometimes it's just a different color. Try it out and see for yourself! diff --git a/locale/ro/knowledge/command-line/how-to-parse-command-line-arguments.md b/locale/ro/knowledge/command-line/how-to-parse-command-line-arguments.md index 611304f041062..0e439bb3e211d 100644 --- a/locale/ro/knowledge/command-line/how-to-parse-command-line-arguments.md +++ b/locale/ro/knowledge/command-line/how-to-parse-command-line-arguments.md @@ -33,7 +33,7 @@ There you have it - an array containing any arguments you passed in. Notice the Where everyday CLI arguments are concerned, you'll want to skip the first two. Now try this in `argv.js`: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); ``` @@ -47,17 +47,17 @@ myArgs: [ 'one', 'two', 'three', 'four' ] Now let's actually do something with the args: ```js -var myArgs = process.argv.slice(2); +const myArgs = process.argv.slice(2); console.log('myArgs: ', myArgs); switch (myArgs[0]) { -case 'insult': + case 'insult': console.log(myArgs[1], 'smells quite badly.'); break; -case 'compliment': + case 'compliment': console.log(myArgs[1], 'is really cool.'); break; -default: + default: console.log('Sorry, that is not something I know how to do.'); } ``` @@ -78,33 +78,32 @@ Once you have it, give it a try - it can really be a life-saver. Lets test it wi const yargs = require('yargs'); const argv = yargs - .command('lyr', 'Tells whether an year is leap year or not', { - year: { - description: 'the year to check for', - alias: 'y', - type: 'number', - } - }) - .option('time', { - alias: 't', - description: 'Tell the present Time', - type: 'boolean', - }) - .help() - .alias('help', 'h') - .argv; + .command('lyr', 'Tells whether an year is leap year or not', { + year: { + description: 'the year to check for', + alias: 'y', + type: 'number' + } + }) + .option('time', { + alias: 't', + description: 'Tell the present Time', + type: 'boolean' + }) + .help() + .alias('help', 'h').argv; if (argv.time) { - console.log('The current time is: ', new Date().toLocaleTimeString()); + console.log('The current time is: ', new Date().toLocaleTimeString()); } if (argv._.includes('lyr')) { - const year = argv.year || new Date().getFullYear(); - if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { - console.log(`${year} is a Leap Year`); - } else { - console.log(`${year} is NOT a Leap Year`); - } + const year = argv.year || new Date().getFullYear(); + if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { + console.log(`${year} is a Leap Year`); + } else { + console.log(`${year} is NOT a Leap Year`); + } } console.log(argv); diff --git a/locale/ro/knowledge/command-line/how-to-prompt-for-command-line-input.md b/locale/ro/knowledge/command-line/how-to-prompt-for-command-line-input.md index 41d2b189fddcf..e76b67f7bcae3 100644 --- a/locale/ro/knowledge/command-line/how-to-prompt-for-command-line-input.md +++ b/locale/ro/knowledge/command-line/how-to-prompt-for-command-line-input.md @@ -16,22 +16,22 @@ Streams are the Node.js way of dealing with evented I/O - it's a big topic, and Here's a simple example. Try the following in a new file: ```js -const readline = require("readline"); +const readline = require('readline'); const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout + input: process.stdin, + output: process.stdout }); -rl.question("What is your name ? ", function(name) { - rl.question("Where do you live ? ", function(country) { - console.log(`${name}, is a citizen of ${country}`); - rl.close(); - }); +rl.question('What is your name ? ', function (name) { + rl.question('Where do you live ? ', function (country) { + console.log(`${name}, is a citizen of ${country}`); + rl.close(); + }); }); -rl.on("close", function() { - console.log("\nBYE BYE !!!"); - process.exit(0); +rl.on('close', function () { + console.log('\nBYE BYE !!!'); + process.exit(0); }); ``` @@ -57,15 +57,17 @@ const prompt = require('prompt'); prompt.start(); prompt.get(['username', 'email'], function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Email: ' + result.email); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Email: ' + result.email); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` @@ -77,29 +79,31 @@ Prompt also makes it trivial to handle a certain set of recurring properties tha const prompt = require('prompt'); const properties = [ - { - name: 'username', - validator: /^[a-zA-Z\s\-]+$/, - warning: 'Username must be only letters, spaces, or dashes' - }, - { - name: 'password', - hidden: true - } + { + name: 'username', + validator: /^[a-zA-Z\s-]+$/, + warning: 'Username must be only letters, spaces, or dashes' + }, + { + name: 'password', + hidden: true + } ]; prompt.start(); prompt.get(properties, function (err, result) { - if (err) { return onErr(err); } - console.log('Command-line input received:'); - console.log(' Username: ' + result.username); - console.log(' Password: ' + result.password); + if (err) { + return onErr(err); + } + console.log('Command-line input received:'); + console.log(' Username: ' + result.username); + console.log(' Password: ' + result.password); }); function onErr(err) { - console.log(err); - return 1; + console.log(err); + return 1; } ``` diff --git a/locale/ro/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md b/locale/ro/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md index 52e993be22934..e5f1d7142bce5 100644 --- a/locale/ro/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md +++ b/locale/ro/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md @@ -12,8 +12,12 @@ layout: knowledge-post.hbs There are two most common built-in timer functions, `setTimeout` and `setInterval`, which can be used to call a function at a later time. For an example usage: ```js -setTimeout(function() { console.log("setTimeout: It's been one second!"); }, 1000); -setInterval(function() { console.log("setInterval: It's been one second!"); }, 1000); +setTimeout(function () { + console.log("setTimeout: It's been one second!"); +}, 1000); +setInterval(function () { + console.log("setInterval: It's been one second!"); +}, 1000); ``` An example output is: @@ -39,9 +43,9 @@ This can cause problems, however, if your server is slow and it takes, for examp ```js const recursive = function () { - console.log("It has been one second!"); - setTimeout(recursive,1000); -} + console.log('It has been one second!'); + setTimeout(recursive, 1000); +}; recursive(); ``` @@ -50,12 +54,12 @@ As you can see, it makes a call to the `recursive` function which, as it complet You can clear the timers you set with `clearTimeout` and `clearInterval`. Their usages are very simple: ```js -function never_call () { - console.log("You should never call this function"); +function neverCall() { + console.log('You should never call this function'); } -const id1 = setTimeout(never_call,1000); -const id2 = setInterval(never_call,1000); +const id1 = setTimeout(neverCall, 1000); +const id2 = setInterval(neverCall, 1000); clearTimeout(id1); clearInterval(id2); @@ -66,8 +70,8 @@ So if you keep track of the return values of the timers, you can easily unhook t The final trick for the timer objects is you can pass parameters to the callback by passing more parameters to setTimeout and setInterval: ```js -setTimeout(console.log, 1000, "This", "has", 4, "parameters"); -setInterval(console.log, 1000, "This only has one"); +setTimeout(console.log, 1000, 'This', 'has', 4, 'parameters'); +setInterval(console.log, 1000, 'This only has one'); ``` The output is: @@ -87,9 +91,9 @@ This only has one `setImmediate()` is another built-in timer function which as the name suggest, runs immediately after the first iteration of the event loop is completed. In other words, `setImmediate()` is similar to a `setTimeout()` function with a `0ms` delay. The `setImmediate()` function can also take extra parameters that are passed when the callback is called: ```js -console.log("This will be printed first"); -setImmediate(console.log, "This is an extra parameter"); -console.log("This will be printed second"); +console.log('This will be printed first'); +setImmediate(console.log, 'This is an extra parameter'); +console.log('This will be printed second'); ``` The output is: diff --git a/locale/ro/knowledge/javascript-conventions/what-is-the-arguments-object.md b/locale/ro/knowledge/javascript-conventions/what-is-the-arguments-object.md index dc85f2e98bed5..c81a314370f7d 100644 --- a/locale/ro/knowledge/javascript-conventions/what-is-the-arguments-object.md +++ b/locale/ro/knowledge/javascript-conventions/what-is-the-arguments-object.md @@ -15,11 +15,11 @@ The `arguments` object is a special construct available inside all function call The `arguments` object is an array-like object. It has a length property that corresponds to the number of arguments passed into the function. You can access these values by indexing into the array, e.g. `arguments[0]` is the first argument. The only other property of `arguments` is callee, which ES5 forbids to use in `strict mode` more about it could be found [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee). Here's an example that illustrates the properties of `arguments`. ```js -const myfunc = function(one) { +const myfunc = function (one) { arguments[0] === one; arguments[1] === 2; arguments.length === 3; -} +}; myfunc(1, 2, 3); ``` @@ -27,10 +27,10 @@ myfunc(1, 2, 3); This construct is very useful and gives JavaScript functions a lot of flexibility. But there is an important gotcha. The `arguments` object behaves like an array, but it is not an actual array. It does not have Array in its prototype chain and it does not respond to any array methods, e.g. `arguments.sort()` raises a TypeError. Instead, you need to copy the values into a true array first. With the advent of ES6 `Array.from()` method this is quite straightforward. ```js -const myfunc = function(a, b, c) { +const myfunc = function (a, b, c) { const args = Array.from(arguments); - console.log(args) // [1, 2, 3] -} + console.log(args); // [1, 2, 3] +}; myfunc(1, 2, 3); ``` @@ -40,10 +40,10 @@ NOTE: For ES5 and below, a normal `for` loop can do the trick. In certain cases you can still treat `arguments` as an array. You can use `arguments` in dynamic function invocations using apply. And most native Array methods will also accept `arguments` when dynamically invoked using call or apply. This technique also suggests another way to convert `arguments` into a true array using the `Array.slice` method. ```js -myfunc.apply(obj, arguments). - -// concat arguments onto the -Array.prototype.concat.apply([1,2,3], arguments); +myfunc + .apply(obj, arguments) + // concat arguments onto the + .Array.prototype.concat.apply([1, 2, 3], arguments); // turn arguments into a true array const args = Array.prototype.slice.call(arguments); @@ -59,7 +59,7 @@ The `arrow functions` were added in the ECMAScript 2015 (ES6) specification as a ```js const myfunc = (...args) => { console.log('first parameter is ', args[0]); -} +}; myfunc(1, 2, 3); ``` diff --git a/locale/zh-cn/docs/guides/buffer-constructor-deprecation.md b/locale/zh-cn/docs/guides/buffer-constructor-deprecation.md index 5e56749e96ee3..b19f490fc147a 100644 --- a/locale/zh-cn/docs/guides/buffer-constructor-deprecation.md +++ b/locale/zh-cn/docs/guides/buffer-constructor-deprecation.md @@ -144,7 +144,7 @@ if (Buffer.from && Buffer.from !== Uint8Array.from) { 对于 Node.js 0.10.x (和之后的版本)支持: ```js -var buf; +let buf; if (Buffer.alloc) { buf = Buffer.alloc(number); } else { diff --git a/locale/zh-cn/docs/guides/domain-postmortem.md b/locale/zh-cn/docs/guides/domain-postmortem.md index cf5125b44b553..298b6307c5d8b 100644 --- a/locale/zh-cn/docs/guides/domain-postmortem.md +++ b/locale/zh-cn/docs/guides/domain-postmortem.md @@ -20,7 +20,9 @@ const c = require('./c'); // module b.js const d = require('domain').create(); -d.on('error', () => { /* silence everything */ }); +d.on('error', () => { + /* silence everything */ +}); d.enter(); // module c.js @@ -40,10 +42,14 @@ const net = require('net'); const d = domain.create(); d.on('error', (err) => console.error(err.message)); -d.run(() => net.createServer((c) => { - c.end(); - c.write('bye'); -}).listen(8000)); +d.run(() => + net + .createServer((c) => { + c.end(); + c.write('bye'); + }) + .listen(8000) +); ``` 即便通过 `d.remove(c)` 手动移除连接也不会阻止连接错误不会自动捕获。 @@ -57,17 +63,19 @@ const d = domain.create(); d.on('error', () => console.error('d intercepted an error')); d.run(() => { - const server = net.createServer((c) => { - const e = domain.create(); // No 'error' handler being set. - e.run(() => { - // This will not be caught by d's error handler. - setImmediate(() => { - throw new Error('thrown from setImmediate'); + const server = net + .createServer((c) => { + const e = domain.create(); // No 'error' handler being set. + e.run(() => { + // This will not be caught by d's error handler. + setImmediate(() => { + throw new Error('thrown from setImmediate'); + }); + // Though this one will bubble to d's error handler. + throw new Error('immediately thrown'); }); - // Though this one will bubble to d's error handler. - throw new Error('immediately thrown'); - }); - }).listen(8080); + }) + .listen(8080); }); ``` @@ -84,21 +92,25 @@ d.run(() => { ```js const d1 = domain.create(); d1.foo = true; // custom member to make more visible in console -d1.on('error', (er) => { /* handle error */ }); +d1.on('error', (er) => { + /* handle error */ +}); -d1.run(() => setTimeout(() => { - const d2 = domain.create(); - d2.bar = 43; - d2.on('error', (er) => console.error(er.message, domain._stack)); - d2.run(() => { - setTimeout(() => { +d1.run(() => + setTimeout(() => { + const d2 = domain.create(); + d2.bar = 43; + d2.on('error', (er) => console.error(er.message, domain._stack)); + d2.run(() => { setTimeout(() => { - throw new Error('outer'); + setTimeout(() => { + throw new Error('outer'); + }); + throw new Error('inner'); }); - throw new Error('inner'); }); - }); -})); + }) +); ``` 即使在域实例被用于本地存储的情况下,使得对资源的访问仍可用,仍然没有办法允许错误从 `d2` 继续传播到 `d1`。快速检查可以告诉我们简单地从 `d2` 域 `'错误'` 处理程序中抛出将允许 `d1` 捕获异常并执行它自己的错误处理程序。虽然不是这种情况。在检查 `domain._stack` 时,您会看到堆栈只包含 `d2` 。 @@ -127,8 +139,7 @@ let uid = 0; // Setting up temporary resources const buf = Buffer.alloc(FILESIZE); -for (let i = 0; i < buf.length; i++) - buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII +for (let i = 0; i < buf.length; i++) buf[i] = ((Math.random() * 1e3) % 78) + 48; // Basic ASCII fs.writeFileSync(FILENAME, buf); function ConnectionResource(c) { @@ -136,7 +147,7 @@ function ConnectionResource(c) { this._connection = c; this._alive = true; this._domain = domain.create(); - this._id = Math.random().toString(32).substr(2).substr(0, 8) + (++uid); + this._id = Math.random().toString(32).substr(2).substr(0, 8) + ++uid; this._domain.add(c); this._domain.on('error', () => { @@ -165,18 +176,24 @@ ConnectionResource.prototype.write = function write(chunk) { }; // Example begin -net.createServer((c) => { - const cr = new ConnectionResource(c); +net + .createServer((c) => { + const cr = new ConnectionResource(c); - const d1 = domain.create(); - fs.open(FILENAME, 'r', d1.intercept((fd) => { - streamInParts(fd, cr, 0); - })); + const d1 = domain.create(); + fs.open( + FILENAME, + 'r', + d1.intercept((fd) => { + streamInParts(fd, cr, 0); + }) + ); - pipeData(cr); + pipeData(cr); - c.on('close', () => cr.end()); -}).listen(8080); + c.on('close', () => cr.end()); + }) + .listen(8080); function streamInParts(fd, cr, pos) { const d2 = domain.create(); @@ -185,24 +202,33 @@ function streamInParts(fd, cr, pos) { print('d2 error:', er.message); cr.end(); }); - fs.read(fd, Buffer.alloc(10), 0, 10, pos, d2.intercept((bRead, buf) => { - if (!cr.isAlive()) { - return fs.close(fd); - } - if (cr._connection.bytesWritten < FILESIZE) { - // Documentation says callback is optional, but doesn't mention that if - // the write fails an exception will be thrown. - const goodtogo = cr.write(buf); - if (goodtogo) { - setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); - } else { - cr._connection.once('drain', () => streamInParts(fd, cr, pos + bRead)); + fs.read( + fd, + Buffer.alloc(10), + 0, + 10, + pos, + d2.intercept((bRead, buf) => { + if (!cr.isAlive()) { + return fs.close(fd); } - return; - } - cr.end(buf); - fs.close(fd); - })); + if (cr._connection.bytesWritten < FILESIZE) { + // Documentation says callback is optional, but doesn't mention that if + // the write fails an exception will be thrown. + const goodtogo = cr.write(buf); + if (goodtogo) { + setTimeout(() => streamInParts(fd, cr, pos + bRead), 1000); + } else { + cr._connection.once('drain', () => + streamInParts(fd, cr, pos + bRead) + ); + } + return; + } + cr.end(buf); + fs.close(fd); + }) + ); } function pipeData(cr) { @@ -244,9 +270,8 @@ process.on('exit', () => { fs.unlinkSync(pipeList[i]); } fs.unlinkSync(FILENAME); - } catch (e) { } + } catch (e) {} }); - ``` * 当一个新的连接发生时,同时也发生: @@ -274,18 +299,20 @@ process.on('exit', () => { const domain = require('domain'); const net = require('net'); -const server = net.createServer((c) => { - // Use a domain to propagate data across events within the - // connection so that we don't have to pass arguments - // everywhere. - const d = domain.create(); - d.data = { connection: c }; - d.add(c); - // Mock class that does some useless async data transformation - // for demonstration purposes. - const ds = new DataStream(dataTransformed); - c.on('data', (chunk) => ds.data(chunk)); -}).listen(8080, () => console.log('listening on 8080')); +const server = net + .createServer((c) => { + // Use a domain to propagate data across events within the + // connection so that we don't have to pass arguments + // everywhere. + const d = domain.create(); + d.data = { connection: c }; + d.add(c); + // Mock class that does some useless async data transformation + // for demonstration purposes. + const ds = new DataStream(dataTransformed); + c.on('data', (chunk) => ds.data(chunk)); + }) + .listen(8080, () => console.log('listening on 8080')); function dataTransformed(chunk) { // FAIL! Because the DataStream instance also created a diff --git a/locale/zh-cn/docs/guides/event-loop-timers-and-nexttick.md b/locale/zh-cn/docs/guides/event-loop-timers-and-nexttick.md index 2f4ba0b1f1ca7..831e7490ffd61 100644 --- a/locale/zh-cn/docs/guides/event-loop-timers-and-nexttick.md +++ b/locale/zh-cn/docs/guides/event-loop-timers-and-nexttick.md @@ -209,8 +209,10 @@ timeout ```js function apiCall(arg, callback) { if (typeof arg !== 'string') - return process.nextTick(callback, - new TypeError('argument should be string')); + return process.nextTick( + callback, + new TypeError('argument should be string') + ); } ``` @@ -225,7 +227,9 @@ function apiCall(arg, callback) { let bar; // this has an asynchronous signature, but calls callback synchronously -function someAsyncApiCall(callback) { callback(); } +function someAsyncApiCall(callback) { + callback(); +} // the callback is called before `someAsyncApiCall` completes. someAsyncApiCall(() => { @@ -289,10 +293,10 @@ server.on('listening', () => {}); ```js const server = net.createServer(); -server.on('connection', (conn) => { }); +server.on('connection', (conn) => {}); server.listen(8080); -server.on('listening', () => { }); +server.on('listening', () => {}); ``` 假设 `listen()` 在事件循环开始时运行,但 listening 的回调被放置在 `setImmediate()` 中。除非传递过主机名,才会立即绑定到端口。为使事件循环继续进行,它必须命中 **轮询** 阶段,这意味着有可能已经接收了一个连接,并在侦听事件之前触发了连接事件。 diff --git a/package-lock.json b/package-lock.json index ad39760cdc050..de0d2ed22def3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -43,6 +43,7 @@ "eslint-config-prettier": "^8.3.0", "eslint-config-semistandard": "^16.0.0", "eslint-plugin-import": "^2.25.3", + "eslint-plugin-markdown": "^2.2.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^4.0.0", "eslint-plugin-promise": "^5.2.0", @@ -2049,6 +2050,173 @@ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", "dev": true }, + "node_modules/eslint-plugin-markdown": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-markdown/-/eslint-plugin-markdown-2.2.1.tgz", + "integrity": "sha512-FgWp4iyYvTFxPwfbxofTvXxgzPsDuSKHQy2S+a8Ve6savbujey+lgrFFbXQA0HPygISpRYWYBjooPzhYSF81iA==", + "dev": true, + "dependencies": { + "mdast-util-from-markdown": "^0.8.5" + }, + "engines": { + "node": "^8.10.0 || ^10.12.0 || >= 12.0.0" + }, + "peerDependencies": { + "eslint": ">=6.0.0" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/character-entities": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-1.2.4.tgz", + "integrity": "sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/character-entities-legacy": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz", + "integrity": "sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/character-reference-invalid": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz", + "integrity": "sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/is-alphabetical": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz", + "integrity": "sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/is-alphanumerical": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz", + "integrity": "sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A==", + "dev": true, + "dependencies": { + "is-alphabetical": "^1.0.0", + "is-decimal": "^1.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/is-decimal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-1.0.4.tgz", + "integrity": "sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/is-hexadecimal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz", + "integrity": "sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw==", + "dev": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/mdast-util-from-markdown": { + "version": "0.8.5", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-0.8.5.tgz", + "integrity": "sha512-2hkTXtYYnr+NubD/g6KGBS/0mFmBcifAsI0yIWRiRo0PjVs6SSOSOdtzbp6kSGnShDN6G5aWZpKQ2lWRy27mWQ==", + "dev": true, + "dependencies": { + "@types/mdast": "^3.0.0", + "mdast-util-to-string": "^2.0.0", + "micromark": "~2.11.0", + "parse-entities": "^2.0.0", + "unist-util-stringify-position": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/mdast-util-to-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-2.0.0.tgz", + "integrity": "sha512-AW4DRS3QbBayY/jJmD8437V1Gombjf8RSOUCMFBuo5iHi58AGEgVCKQ+ezHkZZDpAQS75hcBMpLqjpJTjtUL7w==", + "dev": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/micromark": { + "version": "2.11.4", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-2.11.4.tgz", + "integrity": "sha512-+WoovN/ppKolQOFIAajxi7Lu9kInbPxFuTBVEavFcL8eAfVstoc5MocPmqBeAdBOJV00uaVjegzH4+MA0DN/uA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "dependencies": { + "debug": "^4.0.0", + "parse-entities": "^2.0.0" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/parse-entities": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-2.0.0.tgz", + "integrity": "sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ==", + "dev": true, + "dependencies": { + "character-entities": "^1.0.0", + "character-entities-legacy": "^1.0.0", + "character-reference-invalid": "^1.0.0", + "is-alphanumerical": "^1.0.0", + "is-decimal": "^1.0.0", + "is-hexadecimal": "^1.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/eslint-plugin-markdown/node_modules/unist-util-stringify-position": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-2.0.3.tgz", + "integrity": "sha512-3faScn5I+hy9VleOq/qNbAd6pAx7iH5jYBMS9I1HgQVijz/4mv5Bvw5iw1sC/90CODiKo81G/ps8AJrISn687g==", + "dev": true, + "dependencies": { + "@types/unist": "^2.0.2" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/eslint-plugin-node": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz", @@ -11405,6 +11573,115 @@ } } }, + "eslint-plugin-markdown": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-markdown/-/eslint-plugin-markdown-2.2.1.tgz", + "integrity": "sha512-FgWp4iyYvTFxPwfbxofTvXxgzPsDuSKHQy2S+a8Ve6savbujey+lgrFFbXQA0HPygISpRYWYBjooPzhYSF81iA==", + "dev": true, + "requires": { + "mdast-util-from-markdown": "^0.8.5" + }, + "dependencies": { + "character-entities": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-1.2.4.tgz", + "integrity": "sha512-iBMyeEHxfVnIakwOuDXpVkc54HijNgCyQB2w0VfGQThle6NXn50zU6V/u+LDhxHcDUPojn6Kpga3PTAD8W1bQw==", + "dev": true + }, + "character-entities-legacy": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-1.1.4.tgz", + "integrity": "sha512-3Xnr+7ZFS1uxeiUDvV02wQ+QDbc55o97tIV5zHScSPJpcLm/r0DFPcoY3tYRp+VZukxuMeKgXYmsXQHO05zQeA==", + "dev": true + }, + "character-reference-invalid": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-1.1.4.tgz", + "integrity": "sha512-mKKUkUbhPpQlCOfIuZkvSEgktjPFIsZKRRbC6KWVEMvlzblj3i3asQv5ODsrwt0N3pHAEvjP8KTQPHkp0+6jOg==", + "dev": true + }, + "is-alphabetical": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-1.0.4.tgz", + "integrity": "sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg==", + "dev": true + }, + "is-alphanumerical": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-1.0.4.tgz", + "integrity": "sha512-UzoZUr+XfVz3t3v4KyGEniVL9BDRoQtY7tOyrRybkVNjDFWyo1yhXNGrrBTQxp3ib9BLAWs7k2YKBQsFRkZG9A==", + "dev": true, + "requires": { + "is-alphabetical": "^1.0.0", + "is-decimal": "^1.0.0" + } + }, + "is-decimal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-1.0.4.tgz", + "integrity": "sha512-RGdriMmQQvZ2aqaQq3awNA6dCGtKpiDFcOzrTWrDAT2MiWrKQVPmxLGHl7Y2nNu6led0kEyoX0enY0qXYsv9zw==", + "dev": true + }, + "is-hexadecimal": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-1.0.4.tgz", + "integrity": "sha512-gyPJuv83bHMpocVYoqof5VDiZveEoGoFL8m3BXNb2VW8Xs+rz9kqO8LOQ5DH6EsuvilT1ApazU0pyl+ytbPtlw==", + "dev": true + }, + "mdast-util-from-markdown": { + "version": "0.8.5", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-0.8.5.tgz", + "integrity": "sha512-2hkTXtYYnr+NubD/g6KGBS/0mFmBcifAsI0yIWRiRo0PjVs6SSOSOdtzbp6kSGnShDN6G5aWZpKQ2lWRy27mWQ==", + "dev": true, + "requires": { + "@types/mdast": "^3.0.0", + "mdast-util-to-string": "^2.0.0", + "micromark": "~2.11.0", + "parse-entities": "^2.0.0", + "unist-util-stringify-position": "^2.0.0" + } + }, + "mdast-util-to-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-2.0.0.tgz", + "integrity": "sha512-AW4DRS3QbBayY/jJmD8437V1Gombjf8RSOUCMFBuo5iHi58AGEgVCKQ+ezHkZZDpAQS75hcBMpLqjpJTjtUL7w==", + "dev": true + }, + "micromark": { + "version": "2.11.4", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-2.11.4.tgz", + "integrity": "sha512-+WoovN/ppKolQOFIAajxi7Lu9kInbPxFuTBVEavFcL8eAfVstoc5MocPmqBeAdBOJV00uaVjegzH4+MA0DN/uA==", + "dev": true, + "requires": { + "debug": "^4.0.0", + "parse-entities": "^2.0.0" + } + }, + "parse-entities": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-2.0.0.tgz", + "integrity": "sha512-kkywGpCcRYhqQIchaWqZ875wzpS/bMKhz5HnN3p7wveJTkTtyAB/AlnS0f8DFSqYW1T82t6yEAkEcB+A1I3MbQ==", + "dev": true, + "requires": { + "character-entities": "^1.0.0", + "character-entities-legacy": "^1.0.0", + "character-reference-invalid": "^1.0.0", + "is-alphanumerical": "^1.0.0", + "is-decimal": "^1.0.0", + "is-hexadecimal": "^1.0.0" + } + }, + "unist-util-stringify-position": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-2.0.3.tgz", + "integrity": "sha512-3faScn5I+hy9VleOq/qNbAd6pAx7iH5jYBMS9I1HgQVijz/4mv5Bvw5iw1sC/90CODiKo81G/ps8AJrISn687g==", + "dev": true, + "requires": { + "@types/unist": "^2.0.2" + } + } + } + }, "eslint-plugin-node": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz", diff --git a/package.json b/package.json index 9fc86e2a1a0ce..7302036f461fc 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "eslint-config-prettier": "^8.3.0", "eslint-config-semistandard": "^16.0.0", "eslint-plugin-import": "^2.25.3", + "eslint-plugin-markdown": "^2.2.1", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^4.0.0", "eslint-plugin-promise": "^5.2.0", diff --git a/tests/scripts/CHANGELOG.fixture.withconsole.md b/tests/scripts/CHANGELOG.fixture.withconsole.md index 3a5d20d777696..fbfb51aad90ff 100644 --- a/tests/scripts/CHANGELOG.fixture.withconsole.md +++ b/tests/scripts/CHANGELOG.fixture.withconsole.md @@ -41,7 +41,7 @@ Here's the notable changes as an example for test $ npm run serve ``` ```js -console.log("Hello World"); +console.log('Hello World'); ```