From 58daa0905fe31eba11531995a4d3de6591f370f8 Mon Sep 17 00:00:00 2001 From: XhmikosR Date: Sun, 8 Sep 2019 09:10:28 +0300 Subject: [PATCH] uk: Remove Ukrainian English files. (#2526) There's no need to keep untranslated files, remove them totally. --- locale/uk/about/advisory-board/index.md | 221 ---------------- locale/uk/about/advisory-board/members.md | 66 ----- locale/uk/about/trademark.md | 29 --- locale/uk/about/working-groups.md | 242 ------------------ locale/uk/download/package-manager.md | 237 ----------------- .../how-to-access-query-string-parameters.md | 24 -- .../clients/how-to-create-a-HTTP-request.md | 93 ------- .../servers/how-to-create-a-HTTP-server.md | 33 --- .../servers/how-to-create-a-HTTPS-server.md | 47 ---- .../how-to-handle-multipart-form-data.md | 63 ----- .../HTTP/servers/how-to-read-POST-data.md | 43 ---- .../HTTP/servers/how-to-serve-static-files.md | 42 --- .../REPL/how-to-create-a-custom-repl.md | 100 -------- .../knowledge/REPL/how-to-use-nodejs-repl.md | 58 ----- .../advanced/buffers/how-to-use-buffers.md | 161 ------------ .../how-to-use-fs-create-read-stream.md | 34 --- .../how-to-use-fs-create-write-stream.md | 34 --- .../streams/how-to-use-stream-pipe.md | 88 ------- .../advanced/streams/what-are-streams.md | 42 --- .../how-to-spawn-a-child-process.md | 36 --- .../how-to-get-colors-on-the-command-line.md | 65 ----- .../how-to-parse-command-line-arguments.md | 92 ------- .../how-to-prompt-for-command-line-input.md | 90 ------- .../cryptography/how-to-use-crypto-module.md | 126 --------- .../cryptography/how-to-use-the-tls-module.md | 157 ------------ .../errors/what-are-the-error-conventions.md | 48 ---- .../errors/what-is-the-error-object.md | 42 --- .../uk/knowledge/errors/what-is-try-catch.md | 49 ---- .../how-to-read-files-in-nodejs.md | 53 ---- ...-search-files-and-directories-in-nodejs.md | 41 --- .../how-to-store-local-config-data.md | 83 ------ .../file-system/how-to-use-the-path-module.md | 67 ----- .../how-to-write-files-in-nodejs.md | 50 ---- .../file-system/security/introduction.md | 50 ---- .../how-to-write-asynchronous-code.md | 79 ------ .../control-flow/what-are-callbacks.md | 53 ---- .../control-flow/what-are-event-emitters.md | 101 -------- .../getting-started/globals-in-node-js.md | 27 -- .../how-to-debug-nodejs-applications.md | 92 ------- .../how-to-use-util-inspect.md | 48 ---- .../npm/how-to-access-module-package-info.md | 31 --- .../getting-started/npm/what-is-npm.md | 24 -- .../npm/what-is-the-file-package-json.md | 46 ---- .../getting-started/the-console-module.md | 52 ---- .../getting-started/the-process-module.md | 103 -------- .../what-is-node-core-verus-userland.md | 39 --- .../getting-started/what-is-require.md | 58 ----- .../uk/knowledge/intermediate/how-to-log.md | 92 ------- ...create-default-parameters-for-functions.md | 67 ----- .../using-ECMA5-in-nodejs.md | 97 ------- .../what-are-the-built-in-timer-functions.md | 67 ----- .../what-are-truthy-and-falsy-values.md | 73 ------ .../javascript-conventions/what-is-json.md | 126 --------- .../what-is-the-arguments-object.md | 64 ----- 54 files changed, 4045 deletions(-) delete mode 100644 locale/uk/about/advisory-board/index.md delete mode 100644 locale/uk/about/advisory-board/members.md delete mode 100644 locale/uk/about/trademark.md delete mode 100644 locale/uk/about/working-groups.md delete mode 100644 locale/uk/download/package-manager.md delete mode 100644 locale/uk/knowledge/HTTP/clients/how-to-access-query-string-parameters.md delete mode 100644 locale/uk/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md delete mode 100644 locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md delete mode 100644 locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md delete mode 100644 locale/uk/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md delete mode 100644 locale/uk/knowledge/HTTP/servers/how-to-read-POST-data.md delete mode 100644 locale/uk/knowledge/HTTP/servers/how-to-serve-static-files.md delete mode 100644 locale/uk/knowledge/REPL/how-to-create-a-custom-repl.md delete mode 100644 locale/uk/knowledge/REPL/how-to-use-nodejs-repl.md delete mode 100644 locale/uk/knowledge/advanced/buffers/how-to-use-buffers.md delete mode 100644 locale/uk/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md delete mode 100644 locale/uk/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md delete mode 100644 locale/uk/knowledge/advanced/streams/how-to-use-stream-pipe.md delete mode 100644 locale/uk/knowledge/advanced/streams/what-are-streams.md delete mode 100644 locale/uk/knowledge/child-processes/how-to-spawn-a-child-process.md delete mode 100644 locale/uk/knowledge/command-line/how-to-get-colors-on-the-command-line.md delete mode 100644 locale/uk/knowledge/command-line/how-to-parse-command-line-arguments.md delete mode 100644 locale/uk/knowledge/command-line/how-to-prompt-for-command-line-input.md delete mode 100644 locale/uk/knowledge/cryptography/how-to-use-crypto-module.md delete mode 100644 locale/uk/knowledge/cryptography/how-to-use-the-tls-module.md delete mode 100644 locale/uk/knowledge/errors/what-are-the-error-conventions.md delete mode 100644 locale/uk/knowledge/errors/what-is-the-error-object.md delete mode 100644 locale/uk/knowledge/errors/what-is-try-catch.md delete mode 100644 locale/uk/knowledge/file-system/how-to-read-files-in-nodejs.md delete mode 100644 locale/uk/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md delete mode 100644 locale/uk/knowledge/file-system/how-to-store-local-config-data.md delete mode 100644 locale/uk/knowledge/file-system/how-to-use-the-path-module.md delete mode 100644 locale/uk/knowledge/file-system/how-to-write-files-in-nodejs.md delete mode 100644 locale/uk/knowledge/file-system/security/introduction.md delete mode 100644 locale/uk/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md delete mode 100644 locale/uk/knowledge/getting-started/control-flow/what-are-callbacks.md delete mode 100644 locale/uk/knowledge/getting-started/control-flow/what-are-event-emitters.md delete mode 100644 locale/uk/knowledge/getting-started/globals-in-node-js.md delete mode 100644 locale/uk/knowledge/getting-started/how-to-debug-nodejs-applications.md delete mode 100644 locale/uk/knowledge/getting-started/how-to-use-util-inspect.md delete mode 100644 locale/uk/knowledge/getting-started/npm/how-to-access-module-package-info.md delete mode 100644 locale/uk/knowledge/getting-started/npm/what-is-npm.md delete mode 100644 locale/uk/knowledge/getting-started/npm/what-is-the-file-package-json.md delete mode 100644 locale/uk/knowledge/getting-started/the-console-module.md delete mode 100644 locale/uk/knowledge/getting-started/the-process-module.md delete mode 100644 locale/uk/knowledge/getting-started/what-is-node-core-verus-userland.md delete mode 100644 locale/uk/knowledge/getting-started/what-is-require.md delete mode 100644 locale/uk/knowledge/intermediate/how-to-log.md delete mode 100644 locale/uk/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md delete mode 100644 locale/uk/knowledge/javascript-conventions/using-ECMA5-in-nodejs.md delete mode 100644 locale/uk/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md delete mode 100644 locale/uk/knowledge/javascript-conventions/what-are-truthy-and-falsy-values.md delete mode 100644 locale/uk/knowledge/javascript-conventions/what-is-json.md delete mode 100644 locale/uk/knowledge/javascript-conventions/what-is-the-arguments-object.md diff --git a/locale/uk/about/advisory-board/index.md b/locale/uk/about/advisory-board/index.md deleted file mode 100644 index 7a9b72cf2a03b..0000000000000 --- a/locale/uk/about/advisory-board/index.md +++ /dev/null @@ -1,221 +0,0 @@ ---- -layout: about.hbs -title: Консультативна рада ---- - -# Хартія консультативної ради Node.js - -## 1. Background - -The Node.js open source project is continuing its rapid growth of adoption in -the market. Given the large numbers of contributors, users, and companies with -a stake in the future of the project, the project leadership is looking to -supplement the current governance and contribution mechanisms with an advisory -board, as part of its long-term commitment to create a more open governance -model. - -## 2. Purpose - -### 2.1 - -The primary purpose of the Node.js Advisory Board is to advise Joyent and the -Node.js project core committers team leadership on matters related to -supporting the long-term governance, structure, and roadmap of the Node.js open -source project. The following main areas are included in this charter: - -* Provide a forum for individuals, users, and companies to discuss the issues - under the scope listed below. -* Provide guidance and input to leadership, and where possible, present a - consistent and consolidated opinion from the broader Node.js community. - -### 2.2 - -The Node.js Advisory Board is not: - -* Intended to serve as an authoritative governance board. The Node.js - Advisory Board advises, but does not manage the Node.js project core - committers team leadership. -* Intended to replace existing mechanisms for community input, governance, - or contribution. -* Intended to assume a formal, fiduciary role with respect to the project. - The Node.js Advisory Board members will not be asked to provide funds to - the project, assume liabilities with respect to the project or their - activities, or assume responsibility for enforcing either trademarks or - Node.js Advisory Board recommendations. - -## 3. Scope - -### 3.1 - -The Node.js Advisory Board is expected to provide input and formal -recommendations regarding the following areas: - -* Node.js project long term roadmap -* Node.js project policies and procedures around maintenance, contributions, - core team membership and governance. -* Node.js project policies and procedures around intellectual property, - trademark, and licensing -* Node.js project release schedules - -## 4. Meetings and Memberships - -### 4.1 General - -* The Node.js Advisory Board will have 13 members -* The Node.js core committers project lead: TJ Fontaine -* 2 seats for the top core technical contributors -* Up to 8 additional seats: 4 corporate seats, 4 “user” seats -* One curator seat -* One Open Source Software guidance seat -* No fee or sponsorship is required for membership -* The membership term will last 12 months. With the exception of the Project - Lead, all members can serve a maximum of two consecutive terms - -### 4.2 - -The selection process is intended to be open, transparent, and guided by -objective criteria for membership. - -### 4.3 - -The Curator shall prepare an agenda for and preside over regular meetings of -the Node.js Advisory Board. These meetings shall occur as frequently as the -Node.js Advisory Board determines is in the project’s best interest, but no -less than quarterly. - -### 4.4 - -A member of the Node.js Advisory Board may be removed by a resolution of the -Node.js Advisory Board supported by more than two thirds of its membership. - -### 4.5 - -The Node.js Advisory Board may fill any vacancy arising by removal or -resignation by a simple majority vote to fill the remainder of the term of the -vacating member. - -### 4.6 - -The rules of election and membership outlined in this section may be varied by -a resolution of the Node.js Advisory Board supported by more than two thirds of -its voting membership. - -### 4.7 - -All project contributors are welcome to observe at Node.js Advisory Board -meetings. - -## 5. Selection Process - -### 5.1 Contributors - -Two seats will be granted to the top technical contributors, as measured by -non-trivial pull requests as determined by the core contributor team that have -been merged into the master in the previous 6 months.  These seats will be -reserved for active individual contributors who are neither employees of -Joyent, Inc. nor employees of companies that hold a corporate seat. - -### 5.2 Corporate seats - -Nomination is restricted to companies for whom all three of the following are -true: - -* Are in the top 5 companies in terms of non-trivial pull requests merged - into the master in the past six months as measured by contributions by the - entire organization. -* Have one or more employees for whom a key component of their job - description is to contribute to Node.js and/or make significant - contributions to the Node.js source code base. -* Have committed to integrate Node.js into widely used corporate products in - a manner consistent with Core Criteria listed in Section 8 below. - -### 5.3 - -Once nominations haves been closed, selection of corporate seats will be made -by a vote by eligible contributors. Eligible contributors are those who remain -active as a contributor and have had at least one non-trivial pull request -merged to master in the previous six months. - -### 5.4 User seats - -These seats are for organizations that are using Node.js. To be nominated, an -end-user company must currently be using Node.js in production and have -published a use case on the Node.js website. Once nominations have been -closed, selection will be made by a vote by eligible contributors. Eligible -contributors are those who are currently active and have had at least one -non-trivial pull request merged to master in the past six months. - -## 6. Operation - -### 6.1 - -The Node.js Advisory Board is authorized to seek advice and counsel from other -interested parties and invited experts as appropriate. - -### 6.2 - -Any outside party wishing to bring an issue before the Node.js Advisory Board -may do so by emailing the Node.js Advisory Board at -[advisoryboard@nodejs.org](mailto:advisoryboard@nodejs.org). - -### 6.3 - -The Node.js Advisory Board shall provide transparent and timely reporting -(through any mechanism it deems appropriate) to the Node.js community at large -on all of its activities, subject to the right of any individual to designate -their comments and the ensuing discussion as "in confidence," in which case the -public report shall contain only a note of the request and an agreed summary -(if any) of the substance. - -### 6.4 - -The Node.js Advisory Board is being formed at the discretion of Joyent. Joyent -alone may decide to terminate the Node.js Advisory Board in its sole -discretion; provided however, that Joyent shall first consult the Node.js -Advisory Board and Curator. - -### 6.5 - -The Node.js Advisory Board and its members shall abide by appropriate antitrust -guidelines. - -## 7. Open Governance Principles - -The Node.js Advisory Board will formulate recommendations in conjunction with -the following open governance principles: - -* Open Contributions: anyone should be able to participate and contribute. - All bugs and tasks will be tracked in a public tracker and all of the - source code and all of the tools needed to build it will be available under - an open license permitting unrestricted use. -* Open technical meritocracy: technical merit over pride of authorship. Code - is contributed for the express purpose of advancing technologies relevant - to the project, effectively separating technology advancement from - individual or commercial intent. -* Open design: Roadmaps are discussed in the open, and designs receive input - from all committers and contributors. -* Influence through contribution: organizations and individuals gain - influence over the project through contribution. -* Open Licensing: code is licensed under the MIT license. - -## 8. Core Criteria - -Core Criteria will generally cover such areas as: use of standard APIs, testing -harness, quality assurance, upstream contribution models, and alternative -distributions. - -As Core Criteria will not be fully defined when the initial Node.js Advisory -Board membership is formulated, it is understood that there is a possibility -that certain members of the initial Node.js Advisory Board may not agree with -the Core Criteria when they are fully defined or may have products/offerings -that are not in compliance with the Core Criteria at the time they are -finalized. In this case, the corporate members will either agree to become -compliant within a specified timeframe or else resign their Node.js Advisory -Board position. Read more about the announcement -[https://www.joyent.com/blog/node-js-advisory-board](https://www.joyent.com/blog/node-js-advisory-board). - -Please help us improve this draft by sending your comments and feedback to -[governance@nodejs.org](mailto:governance@nodejs.org). - -The source for this document can be found [in this -repository](https://github.com/nodejs/nodejs.org/blob/master/locale/en/about/advisory-board/index.md). diff --git a/locale/uk/about/advisory-board/members.md b/locale/uk/about/advisory-board/members.md deleted file mode 100644 index f0d07cc63c054..0000000000000 --- a/locale/uk/about/advisory-board/members.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -layout: about.hbs -title: Члени консультативної ради ---- - -# Члени консультативної ради - -## Bert Belder - -* StrongLoop, Inc. - -## Danese Cooper - -* Expert in Open Source Communities - -## Kevin Decker - -* Walmart - -## TJ Fontaine - -* Joyent - -## Dav Glass - -* Yahoo - -## Scott Hammond - -* Joyent - -## Cian Ó Maidín - -* nearForm - -## Todd M. Moore - -* IBM - -## Gianugo Rabellino - -* Microsoft Open Technologies, Inc. - -## Issac Roth - -* StrongLoop, Inc. - -## Chris Saint-Amant - -* Netflix - -## Isaac Schlueter - -* npm - -## Dan Shaw - -* NodeSource - -## Erik Toth - -* PayPal - -## Chris Williams - -* Emerging Technology Advisors diff --git a/locale/uk/about/trademark.md b/locale/uk/about/trademark.md deleted file mode 100644 index cddb5fb946903..0000000000000 --- a/locale/uk/about/trademark.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -layout: about.hbs -title: Політика торгової марки ---- - -# Політика торгової марки - -The Node.js trademarks, service marks, and graphics marks are symbols of the -quality, performance, and ease of use that people have come to associate with -the Node.js software and project. To ensure that the Node.js marks continue to -symbolize these qualities, we must ensure that the marks are only used in ways -that do not mislead people or cause them to confuse Node.js with other software -of lower quality. If we don’t ensure the marks are used in this way, it cannot -only confuse users, it can make it impossible to use the mark to protect -against people who maliciously exploit the mark in the future. The primary goal -of this policy is to make sure that this doesn’t happen to the Node.js mark, so -that the community and users of Node.js are always protected in the future. - -At the same time, we’d like community members to feel comfortable spreading the -word about Node.js and participating in the Node.js community. Keeping that -goal in mind, we’ve tried to make the policy as flexible and easy to understand -as legally possible. - -Please read the [full policy](/static/documents/trademark-policy.pdf). -If you have any questions don't hesitate to -[email us](mailto:trademark@nodejs.org). - -Guidelines for the visual display of the Node.js mark are described in -the [Visual Guidelines](/static/documents/foundation-visual-guidelines.pdf). diff --git a/locale/uk/about/working-groups.md b/locale/uk/about/working-groups.md deleted file mode 100644 index c02d4dff1055e..0000000000000 --- a/locale/uk/about/working-groups.md +++ /dev/null @@ -1,242 +0,0 @@ ---- -layout: about.hbs -title: Робочі групи ---- - -# Core Working Groups - - -Core Working Groups are created by the -[Technical Steering Committee (TSC)](https://github.com/nodejs/TSC/blob/master/TSC-Charter.md). - -## Current Working Groups - -* [Addon API](#addon-api) -* [Benchmarking](#benchmarking) -* [Build](#build) -* [Diagnostics](#diagnostics) -* [Docker](#docker) -* [Evangelism](#evangelism) -* [i18n](#i18n) -* [Release](#release) -* [Security](#security) -* [Streams](#streams) -* [Website](#website) - -### [Addon API](https://github.com/nodejs/nan) - -The Addon API Working Group is responsible for maintaining the NAN project and -corresponding _nan_ package in npm. The NAN project makes available an -abstraction layer for native add-on authors for Node.js, -assisting in the writing of code that is compatible with many actively used -versions of Node.js, V8 and libuv. - -Responsibilities include: -* Maintaining the [NAN](https://github.com/nodejs/nan) GitHub repository, - including code, issues and documentation. -* Maintaining the [addon-examples](https://github.com/nodejs/node-addon-examples) - GitHub repository, including code, issues and documentation. -* Maintaining the C++ Addon API within the Node.js project, in subordination to - the Node.js TSC. -* Maintaining the Addon documentation within the Node.js project, in - subordination to the Node.js TSC. -* Maintaining the _nan_ package in npm, releasing new versions as appropriate. -* Messaging about the future of the Node.js and NAN interface to give the - community advance notice of changes. - -The current members can be found in their -[README](https://github.com/nodejs/nan#collaborators). - -### [Benchmarking](https://github.com/nodejs/benchmarking) - -The purpose of the Benchmark Working Group is to gain consensus -on an agreed set of benchmarks that can be used to: - -* track and evangelize performance gains made between Node.js releases -* avoid performance regressions between releases - -Responsibilities include: -* Identifying 1 or more benchmarks that reflect customer usage. - Likely will need more than one to cover typical Node.js use cases - including low-latency and high concurrency -* Working to get community consensus on the list chosen -* Adding regular execution of chosen benchmarks to Node.js builds -* Tracking/publicizing performance between builds/releases - -### [Build](https://github.com/nodejs/build) - -The Build Working Group's purpose is to create and maintain a distributed -automation infrastructure. - -Responsibilities include: -* Producing packages for all target platforms. -* Running tests. -* Running performance testing and comparisons. -* Creating and managing build-containers. - -### [Diagnostics](https://github.com/nodejs/diagnostics) - -The Diagnostics Working Group's purpose is to surface a set of comprehensive, -documented, and extensible diagnostic interfaces for use by Node.js tools and -JavaScript VMs. - -Responsibilities include: -* Collaborating with V8 to integrate `v8_inspector` into Node.js. -* Collaborating with V8 to integrate `trace_event` into Node.js. -* Collaborating with Core to refine `async_wrap` and `async_hooks`. -* Maintaining and improving OS trace system integration (e.g. ETW, LTTNG, dtrace). -* Documenting diagnostic capabilities and APIs in Node.js and its components. -* Exploring opportunities and gaps, discussing feature requests, and addressing - conflicts in Node.js diagnostics. -* Fostering an ecosystem of diagnostics tools for Node.js. -* Defining and adding interfaces/APIs in order to allow dumps to be generated - when needed. -* Defining and adding common structures to the dumps generated in order to - support tools that want to introspect those dumps. - -### [Docker](https://github.com/nodejs/docker-node) - -The Docker Working Group's purpose is to build, maintain, and improve official -Docker images for the Node.js project. - -Responsibilities include: -* Keeping the official Docker images updated in line with new Node.js releases. -* Decide and implement image improvements and/or fixes. -* Maintain and improve the images' documentation. - -### [Evangelism](https://github.com/nodejs/evangelism) - -The Evangelism Working Group promotes the accomplishments -of Node.js and lets the community know how they can get involved. - -Responsibilities include: -* Facilitating project messaging. -* Managing official project social media. -* Handling the promotion of speakers for meetups and conferences. -* Handling the promotion of community events. -* Publishing regular update summaries and other promotional - content. - -### [i18n](https://github.com/nodejs/i18n) - -The i18n Working Groups handle more than just translations. They -are endpoints for community members to collaborate with each -other in their language of choice. - -Each team is organized around a common spoken language. Each -language community might then produce multiple localizations for -various project resources. - -Responsibilities include: -* Translating any Node.js materials they believe are relevant to their - community. -* Reviewing processes for keeping translations up to date and of high quality. -* Managing and monitoring social media channels in their language. -* Promoting Node.js speakers for meetups and conferences in their language. - -Each language community maintains its own membership. - -* [nodejs-ar - Arabic (العَرَبِيَّة)](https://github.com/nodejs/nodejs-ar) -* [nodejs-bg - Bulgarian (български)](https://github.com/nodejs/nodejs-bg) -* [nodejs-bn - Bengali (বাংলা)](https://github.com/nodejs/nodejs-bn) -* [nodejs-zh-CN - Chinese (中文)](https://github.com/nodejs/nodejs-zh-CN) -* [nodejs-cs - Czech (Čeština)](https://github.com/nodejs/nodejs-cs) -* [nodejs-da - Danish (Dansk)](https://github.com/nodejs/nodejs-da) -* [nodejs-de - German (Deutsch)](https://github.com/nodejs/nodejs-de) -* [nodejs-el - Greek (Ελληνικά)](https://github.com/nodejs/nodejs-el) -* [nodejs-es - Spanish (Español)](https://github.com/nodejs/nodejs-es) -* [nodejs-fa - Persian (فارسی)](https://github.com/nodejs/nodejs-fa) -* [nodejs-fi - Finnish (Suomi)](https://github.com/nodejs/nodejs-fi) -* [nodejs-fr - French (Français)](https://github.com/nodejs/nodejs-fr) -* [nodejs-he - Hebrew (עברית)](https://github.com/nodejs/nodejs-he) -* [nodejs-hi - Hindi (हिन्दी)](https://github.com/nodejs/nodejs-hi) -* [nodejs-hu - Hungarian (Magyar)](https://github.com/nodejs/nodejs-hu) -* [nodejs-id - Indonesian (Bahasa Indonesia)](https://github.com/nodejs/nodejs-id) -* [nodejs-it - Italian (Italiano)](https://github.com/nodejs/nodejs-it) -* [nodejs-ja - Japanese (日本語)](https://github.com/nodejs/nodejs-ja) -* [nodejs-ka - Georgian (ქართული)](https://github.com/nodejs/nodejs-ka) -* [nodejs-ko - Korean (한국어)](https://github.com/nodejs/nodejs-ko) -* [nodejs-mk - Macedonian (Македонски)](https://github.com/nodejs/nodejs-mk) -* [nodejs-ms - Malay (بهاس ملايو‎)](https://github.com/nodejs/nodejs-ms) -* [nodejs-nl - Dutch (Nederlands)](https://github.com/nodejs/nodejs-nl) -* [nodejs-no - Norwegian (Norsk)](https://github.com/nodejs/nodejs-no) -* [nodejs-pl - Polish (Język Polski)](https://github.com/nodejs/nodejs-pl) -* [nodejs-pt - Portuguese (Português)](https://github.com/nodejs/nodejs-pt) -* [nodejs-ro - Romanian (Română)](https://github.com/nodejs/nodejs-ro) -* [nodejs-ru - Russian (Русский)](https://github.com/nodejs/nodejs-ru) -* [nodejs-sv - Swedish (Svenska)](https://github.com/nodejs/nodejs-sv) -* [nodejs-ta - Tamil (தமிழ்)](https://github.com/nodejs/nodejs-ta) -* [nodejs-tr - Turkish (Türkçe)](https://github.com/nodejs/nodejs-tr) -* [nodejs-zh-TW - Taiwanese (國語)](https://github.com/nodejs/nodejs-zh-TW) -* [nodejs-uk - Ukrainian (Українська)](https://github.com/nodejs/nodejs-uk) -* [nodejs-vi - Vietnamese (Tiếng Việt)](https://github.com/nodejs/nodejs-vi) - -### [Release](https://github.com/nodejs/LTS) -The Release Working Group manages the release process for Node.js. - -Responsibilities include: -* Define the release process. -* Define the content of releases. -* Generate and create releases. -* Test Releases. -* Manage the Long Term Support and Current branches including - backporting changes to these branches. -* Define the policy for what gets backported to release streams - -### [Security](https://github.com/nodejs/security-wg) - -The Security Working Group manages all aspects and processes linked to Node.js security. - -Responsibilities include: -* Define and maintain security policies and procedures for: - * the core Node.js project - * other projects maintained by the Node.js Technical Steering Committee (TSC). -* Work with the Node Security Platform to bring community vulnerability data into - the foundation as a shared asset. -* Ensure the vulnerability data is updated in an efficient and timely manner. - For example, ensuring there are well-documented processes for reporting - vulnerabilities in community modules. -* Review and recommend processes for handling of security reports (but not the - actual administration of security reports, which are reviewed by a group of people - directly delegated to by the TSC). -* Define and maintain policies and procedures for the coordination of security - concerns within the external Node.js open source ecosystem. -* Offer help to npm package maintainers to fix high-impact security bugs. -* Maintain and make available data on disclosed security vulnerabilities in: - * the core Node.js project - * other projects maintained by the Node.js Foundation technical group - * the external Node.js open source ecosystem -* Promote the improvement of security practices within the Node.js ecosystem. -* Recommend security improvements for the core Node.js project. -* Facilitate and promote the expansion of a healthy security service and product - provider ecosystem. - -### [Streams](https://github.com/nodejs/readable-stream) - -The Streams Working Group is dedicated to the support and improvement of the -Streams API as used in Node.js and the npm ecosystem. We seek to create a -composable API that solves the problem of representing multiple occurrences -of an event over time in a humane, low-overhead fashion. Improvements to the -API will be driven by the needs of the ecosystem; interoperability and -backwards compatibility with other solutions and prior versions are paramount -in importance. - -Responsibilities include: -* Addressing stream issues on the Node.js issue tracker. -* Authoring and editing stream documentation within the Node.js project. -* Reviewing changes to stream subclasses within the Node.js project. -* Redirecting changes to streams from the Node.js project to this project. -* Assisting in the implementation of stream providers within Node.js. -* Recommending versions of `readable-stream` to be included in Node.js. -* Messaging about the future of streams to give the community advance notice of changes. - -### [Website](https://github.com/nodejs/nodejs.org) - -The Website Working Group's purpose is to build and maintain a public -website for the Node.js project. - -Responsibilities include: -* Developing and maintaining a build and automation system for nodejs.org. -* Ensuring the site is regularly updated with changes made to Node.js, like - releases and features. -* Fostering and enabling a community of translators. diff --git a/locale/uk/download/package-manager.md b/locale/uk/download/package-manager.md deleted file mode 100644 index eadedf27977ac..0000000000000 --- a/locale/uk/download/package-manager.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: page.hbs -title: Installing Node.js via package manager ---- - -# Installing Node.js via package manager - -***Note:*** The packages on this page are maintained and supported by their respective packagers, **not** the Node.js core team. Please report any issues you encounter to the package maintainer. If it turns out your issue is a bug in Node.js itself, the maintainer will report the issue upstream. - ----------------------------- - -* [Android](#android) -* [Arch Linux](#arch-linux) -* [Debian and Ubuntu based Linux distributions, Enterprise Linux/Fedora and Snap packages](#debian-and-ubuntu-based-linux-distributions-enterprise-linux-fedora-and-snap-packages) -* [FreeBSD](#freebsd) -* [Gentoo](#gentoo) -* [NetBSD](#netbsd) -* [nvm](#nvm) -* [OpenBSD](#openbsd) -* [openSUSE and SLE](#opensuse-and-sle) -* [macOS](#macos) -* [SmartOS and illumos](#smartos-and-illumos) -* [Solus](#solus) -* [Void Linux](#void-linux) -* [Windows](#windows) - ----------------------------- - -## Android - -Android support is still experimental in Node.js, so precompiled binaries are not yet provided by Node.js developers. - -However, there are some third-party solutions. For example, [Termux](https://termux.com/) community provides terminal emulator and Linux environment for Android, as well as own package manager and [extensive collection](https://github.com/termux/termux-packages) of many precompiled applications. This command in Termux app will install the last available Node.js version: - -```bash -pkg install nodejs -``` - -Currently, Termux Node.js binaries are linked against `system-icu` (depending on `libicu` package). - -## Arch Linux - -Node.js and npm packages are available in the Community Repository. - -```bash -pacman -S nodejs npm -``` - -## Debian and Ubuntu based Linux distributions, Enterprise Linux/Fedora and Snap packages - -[Official Node.js binary distributions](https://github.com/nodesource/distributions/blob/master/README.md) are provided by NodeSource. - -## FreeBSD - -The most recent release of Node.js is available via the [www/node](https://www.freshports.org/www/node) port. - -Install a binary package via [pkg](https://www.freebsd.org/cgi/man.cgi?pkg): - -```bash -pkg install node -``` - -Or compile it on your own using [ports](https://www.freebsd.org/cgi/man.cgi?ports): - -```bash -cd /usr/ports/www/node && make install -``` - -## Gentoo - -Node.js is available in the portage tree. - -```bash -emerge nodejs -``` - -## NetBSD - -Node.js is available in the pkgsrc tree: - -```bash -cd /usr/pkgsrc/lang/nodejs && make install -``` - -Or install a binary package (if available for your platform) using pkgin: - -```bash -pkgin -y install nodejs -``` - -## nvm -Node Version Manager is a bash script used to manage multiple released Node.js versions. It allows -you to perform operations like install, uninstall, switch version, etc. -To install nvm, use this [install script](https://github.com/creationix/nvm#install-script). - -On Unix / OS X systems Node.js built from source can be installed using -[nvm](https://github.com/creationix/nvm) by installing into the location that nvm expects: - -```bash -env VERSION=`python tools/getnodeversion.py` make install DESTDIR=`nvm_version_path v$VERSION` PREFIX="" -``` - -After this you can use `nvm` to switch between released versions and versions -built from source. -For example, if the version of Node.js is v8.0.0-pre: - -```bash -nvm use 8 -``` - -Once the official release is out you will want to uninstall the version built -from source: - -```bash -nvm uninstall 8 -``` - -## OpenBSD - -Node.js is available through the ports system. - -```bash -/usr/ports/lang/node -``` - -Using [pkg_add](https://man.openbsd.org/OpenBSD-current/man1/pkg_add.1) on OpenBSD: - -```bash -pkg_add node -``` - -## openSUSE and SLE - -Node.js is available in the main repositories under the following packages: - -* **openSUSE Leap 42.2**: `nodejs4` -* **openSUSE Leap 42.3**: `nodejs4`, `nodejs6` -* **openSUSE Tumbleweed**: `nodejs4`, `nodejs6`, `nodejs8` -* **SUSE Linux Enterprise Server (SLES) 12**: `nodejs4`, `nodejs6` - (The "Web and Scripting Module" must be [added before installing](https://www.suse.com/documentation/sles-12/book_sle_deployment/data/sec_add-ons_extensions.html).) - -For example, to install Node.js 4.x on openSUSE Leap 42.2, run the following as root: - -```bash -zypper install nodejs4 -``` - -## macOS - -Simply download the [macOS Installer](https://nodejs.org/#download) direct from the [nodejs.org](https://nodejs.org) web site. - -_If you want to download the package with bash:_ - -```bash -curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/" -``` - -### Alternatives - -Using **[Homebrew](https://brew.sh/)**: - -```bash -brew install node -``` - -Using **[MacPorts](https://www.macports.org/)**: - -```bash -port install nodejs - -# Example -port install nodejs7 -``` - -Using **[pkgsrc](https://pkgsrc.joyent.com/install-on-osx/)**: - -Install the binary package: - -```bash -pkgin -y install nodejs -``` - -Or build manually from pkgsrc: - -```bash -cd pkgsrc/lang/nodejs && bmake install -``` - -## SmartOS and illumos - -SmartOS images come with pkgsrc pre-installed. On other illumos distributions, first install **[pkgsrc](https://pkgsrc.joyent.com/install-on-illumos/)**, then you may install the binary package as normal: - -```bash -pkgin -y install nodejs -``` - -Or build manually from pkgsrc: - -```bash -cd pkgsrc/lang/nodejs && bmake install -``` - -## Solus - -Solus provides node.js in its main repository. - -```bash -sudo eopkg install nodejs -``` - -## Void Linux - -Void Linux ships node.js stable in the main repository. - -```bash -xbps-install -Sy nodejs -``` - -## Windows - -Simply download the [Windows Installer](https://nodejs.org/#download) directly from the [nodejs.org](https://nodejs.org) web site. - -### Alternatives - -Using **[Chocolatey](https://chocolatey.org/)**: - -```bash -cinst nodejs -# or for full install with npm -cinst nodejs.install -``` - -Using **[Scoop](https://scoop.sh/)**: - -```bash -scoop install nodejs -``` diff --git a/locale/uk/knowledge/HTTP/clients/how-to-access-query-string-parameters.md b/locale/uk/knowledge/HTTP/clients/how-to-access-query-string-parameters.md deleted file mode 100644 index 5beb57a6986e3..0000000000000 --- a/locale/uk/knowledge/HTTP/clients/how-to-access-query-string-parameters.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: How to access query string parameters -date: '2011-08-26T10:08:50.000Z' -tags: - - http -difficulty: 1 -layout: knowledge-post.hbs ---- - -In Node.js, functionality to aid in the accessing of URL query string parameters is built into the standard library. The built-in `url.parse` method takes care of most of the heavy lifting for us. Here is an example script using this handy function and an explanation on how it works: - - var fs = require('fs'); - var http = require('http'); - var url = require('url') ; - - http.createServer(function (req, res) { - var queryObject = url.parse(req.url,true).query; - console.log(queryObject); - - res.writeHead(200); - res.end('Feel free to add query parameters to the end of the url'); - }).listen(8080); - -The key part of this whole script is this line: `var queryObject = url.parse(req.url,true).query;`. Let's take a look at things from the inside-out. First off, `req.url` will look like `/app.js?foo=bad&baz=foo`. This is the part that is in the URL bar of the browser. Next, it gets passed to `url.parse` which parses out the various elements of the URL (NOTE: the second paramater is a boolean stating whether the method should parse the query string, so we set it to true). Finally, we access the `.query` property, which returns us a nice, friendly JavaScript object with our query string data. diff --git a/locale/uk/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md b/locale/uk/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md deleted file mode 100644 index 44b9ad4f1f31e..0000000000000 --- a/locale/uk/knowledge/HTTP/clients/how-to-create-a-HTTP-request.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: How do I make a http request? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - http -difficulty: 2 -layout: knowledge-post.hbs ---- - -Another extremely common programming task is making an HTTP request to a web server. Node.js provides an extremely simple API for this functionality in the form of `http.request`. - -As an example, we are going to preform a GET request to [www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new](www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new) (which returns a random integer between 1 and 10) and print the result to the console. - - var http = require('http'); - - //The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new' - var options = { - host: 'www.random.org', - path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new' - }; - - callback = function(response) { - var str = ''; - - //another chunk of data has been received, so append it to `str` - response.on('data', function (chunk) { - str += chunk; - }); - - //the whole response has been received, so we just print it out here - response.on('end', function () { - console.log(str); - }); - } - - http.request(options, callback).end(); - -Making a POST request is just as easy. We will make a POST request to `www.nodejitsu.com:1337` which is running a server that will echo back what we post. The code for making a POST request is almost identical to making a GET request, just a few simple modifications: - - var http = require('http'); - - //The url we want is `www.nodejitsu.com:1337/` - var options = { - host: 'www.nodejitsu.com', - path: '/', - //since we are listening on a custom port, we need to specify it by hand - port: '1337', - //This is what changes the request to a POST request - method: 'POST' - }; - - callback = function(response) { - var str = '' - response.on('data', function (chunk) { - str += chunk; - }); - - response.on('end', function () { - console.log(str); - }); - } - - var req = http.request(options, callback); - //This is the data we are posting, it needs to be a string or a buffer - req.write("hello world!"); - req.end(); - -Throwing in custom headers is just a tiny bit harder. On `www.nodejitsu.com:1338` we are running a server that will print out the `custom` header. So we will just make a quick request to it: - - var http = require('http'); - - var options = { - host: 'www.nodejitsu.com', - path: '/', - port: '1338', - //This is the only line that is new. `headers` is an object with the headers to request - headers: {'custom': 'Custom Header Demo works'} - }; - - callback = function(response) { - var str = '' - response.on('data', function (chunk) { - str += chunk; - }); - - response.on('end', function () { - console.log(str); - }); - } - - var req = http.request(options, callback); - req.end(); diff --git a/locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md b/locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md deleted file mode 100644 index 16fd0b9104415..0000000000000 --- a/locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTP-server.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: How do I create a HTTP server? -date: '2011-08-26T10:08:50.000Z' -tags: - - http -difficulty: 1 -layout: knowledge-post.hbs ---- - -Making a simple HTTP server in Node.js has become the de facto 'hello world' for the platform. On the one hand, Node.js provides extremely easy-to-use HTTP APIs; on the other hand, a simple web server also serves as an excellent demonstration of Node's asynchronous strengths. - -Let's take a look at a very simple example: - - var http = require('http'); - var requestListener = function (req, res) { - res.writeHead(200); - res.end('Hello, World!\n'); - } - - var server = http.createServer(requestListener); - server.listen(8080); - -Save this in a file called `server.js` - run `node server.js`, and your program will hang there... it's waiting for connections to respond to, so you'll have to give it one if you want to see it do anything. Try opening up a browser, and typing `localhost:8080` into the location bar. If everything has been set up correctly, you should see your server saying hello! - -Let's take a more in-depth look at what the above code is doing. First, a function is defined called `requestListener` that takes a request object and a response object as parameters. - -The request object contains things such as the requested URL, but in this example we ignore it and always return "Hello World". - -The response object is how we send the headers and contents of the response back to the user making the request. Here we return a 200 response code (signaling a successful response) with the body "Hello World". Other headers, such as `Content-type`, would also be set here. - -Next, the `http.createServer` method creates a server that calls `requestListener` whenever a request comes in. The next line, `server.listen(8080)`, calls the `listen` method, which causes the server to wait for incoming requests on the specified port - 8080, in this case. - -There you have it - your most basic Node.js HTTP server. diff --git a/locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md b/locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md deleted file mode 100644 index 0a2ac0f03a86c..0000000000000 --- a/locale/uk/knowledge/HTTP/servers/how-to-create-a-HTTPS-server.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: How to create an https server? -date: '2011-08-26T10:08:50.000Z' -tags: - - https -difficulty: 1 -layout: knowledge-post.hbs ---- - -*If you're using [Nodejitsu](http://nodejitsu.com)*, we handle HTTPS for you. Free SSL on jit.su and nodejitsu.com subdomains, and SSL on custom domains for business customers. -*It's never necessary to create an HTTPS server yourself.* - -- - - - -To create an HTTPS server, you need two things: an SSL certificate, and Node's built-in `https` module. - -We need to start out with a word about SSL certificates. Speaking generally, there are two kinds of certificates: those signed by a 'Certificate Authority', or CA, and 'self-signed certificates'. A Certificate Authority is a trusted source for an SSL certificate, and using a certificate from a CA allows your users to be trust the identity of your website. In most cases, you would want to use a CA-signed certificate in a production environment - for testing purposes, however, a self-signed certicate will do just fine. - -To generate a self-signed certificate, run the following in your shell: - - openssl genrsa -out key.pem - openssl req -new -key key.pem -out csr.pem - openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem - rm csr.pem - -This should leave you with two files, `cert.pem` (the certificate) and `key.pem` (the private key). This is all you need for a SSL connection. So now you set up a quick hello world example (the biggest difference between https and [http](/how-do-i-create-a-http-server) is the `options` parameter): - - var https = require('https'); - var fs = require('fs'); - - var options = { - key: fs.readFileSync('key.pem'), - cert: fs.readFileSync('cert.pem') - }; - - var a = https.createServer(options, function (req, res) { - res.writeHead(200); - res.end("hello world\n"); - }).listen(8000); - -NODE PRO TIP: Note `fs.readFileSync` - unlike `fs.readFile`, `fs.readFileSync` will block the entire process until it completes. In situations like this - loading vital configuration data - the `sync` functions are okay. In a busy server, however, using a synchronous function during a request will force the server to deal with the requests one by one! - -Now that your server is set up and started, you should be able to get the file with curl: - - curl -k https://localhost:8000 - -or in your browser, by going to https://localhost:8000 . diff --git a/locale/uk/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md b/locale/uk/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md deleted file mode 100644 index bba72f6901d83..0000000000000 --- a/locale/uk/knowledge/HTTP/servers/how-to-handle-multipart-form-data.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: How to handle multipart form data -date: '2011-09-09T10:08:50.000Z' -tags: - - http - - forms - - multipart - - uploads -difficulty: 3 -layout: knowledge-post.hbs ---- - -Handling form data and file uploads properly is an important and complex problem in HTTP servers. Doing it by hand would involve parsing streaming binary data, writing it to the file system, parsing out other form data, and several other complex concerns - luckily, only a very few people will need to worry about it on that deep level. Felix Geisendorfer, one of the Node.js core committers, wrote a library called `node-formidable` that handles all the hard parts for you. With its friendly API, you can be parsing forms and receiving file uploads in no time. - -This example is taken directly from the `node-formidable` GitHub page, with some additional explanation added. - - var formidable = require('formidable'), - http = require('http'), - util = require('util'); - - http.createServer(function(req, res) { - - // This if statement is here to catch form submissions, and initiate multipart form data parsing. - - if (req.url == '/upload' && req.method.toLowerCase() == 'post') { - - // Instantiate a new formidable form for processing. - - var form = new formidable.IncomingForm(); - - // form.parse analyzes the incoming stream data, picking apart the different fields and files for you. - - form.parse(req, function(err, fields, files) { - if (err) { - - // Check for and handle any errors here. - - console.error(err.message); - return; - } - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received upload:\n\n'); - - // This last line responds to the form submission with a list of the parsed data and files. - - res.end(util.inspect({fields: fields, files: files})); - }); - return; - } - - // If this is a regular request, and not a form submission, then send the form. - - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
'+ - '
'+ - '
'+ - ''+ - '
' - ); - }).listen(8080); - -Try it out for yourself - it's definitely the simpler solution, and `node-formidable` is a battle-hardened, production-ready library. Let userland solve problems like this for you, so that you can get back to writing the rest of your code! diff --git a/locale/uk/knowledge/HTTP/servers/how-to-read-POST-data.md b/locale/uk/knowledge/HTTP/servers/how-to-read-POST-data.md deleted file mode 100644 index 55e307dee7062..0000000000000 --- a/locale/uk/knowledge/HTTP/servers/how-to-read-POST-data.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: How can I read POST data? -date: '2011-08-26T10:08:50.000Z' -tags: - - http -difficulty: 1 -layout: knowledge-post.hbs ---- - -Reading the data from a POST request (i.e. a form submission) can be a little bit of a pitfall in Node.js, so we're going to go through an example of how to do it properly. The first step, obviously, is to listen for incoming data - the trick is to wait for the data to finish, so that you can process all the form data without losing anything. - -Here is a quick script that shows you how to do exactly that: - - var http = require('http'); - var postHTML = - 'Post Example' + - '' + - '
' + - 'Input 1:
' + - 'Input 2:
' + - '' + - '
' + - ''; - - http.createServer(function (req, res) { - var body = ""; - req.on('data', function (chunk) { - body += chunk; - }); - req.on('end', function () { - console.log('POSTed: ' + body); - res.writeHead(200); - res.end(postHTML); - }); - }).listen(8080); - -The variable `postHTML` is a static string containing the HTML for two input boxes and a submit box - this HTML is provided so that you can `POST` example data. This is NOT the right way to serve static HTML - please see [How to Serve Static Files](link) for a more proper example. - -With the HTML out of the way, we [create a server](/how-do-i-create-a-http-server) to listen for requests. It is important to note, when listening for POST data, that the `req` object is also an [Event Emitter](/what-are-event-emitters). `req`, therefore, will emit a `data` event whenever a 'chunk' of incoming data is received; when there is no more incoming data, the `end` event is emitted. So, in our case, we listen for `data` events. Once all the data is received, we log the data to the console and send the response. - -Something important to note is that the event listeners are being added immediately after the request object is received. If you don't immediately set them, then there is a possibility of missing some of the events. If, for example, an event listener was attached from inside a callback, then the `data` and `end` events might be fired in the meantime with no listeners attached! - -You can save this script to `server.js` and run it with `node server.js`. Once you run it you will notice that occasionally you will see lines with no data, e.g. `POSTed:`. This happens because regular `GET` requests go through the same codepath. In a more 'real-world' application, it would be proper practice to check the type of request and handle the different request types differently. diff --git a/locale/uk/knowledge/HTTP/servers/how-to-serve-static-files.md b/locale/uk/knowledge/HTTP/servers/how-to-serve-static-files.md deleted file mode 100644 index 612088bea4d91..0000000000000 --- a/locale/uk/knowledge/HTTP/servers/how-to-serve-static-files.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: How to serve static files -date: '2011-08-26T10:08:50.000Z' -tags: - - http -difficulty: 1 -layout: knowledge-post.hbs ---- - -A basic necessity for most [http servers](/how-do-i-create-a-https-server) is to be able to serve static files. Thankfully, it is not that hard to do in Node.js. First you [link]read the file, then you serve the file. Here is an example of a script that will serve the files in the current directory: - - var fs = require('fs'), - http = require('http'); - - http.createServer(function (req, res) { - fs.readFile(__dirname + req.url, function (err,data) { - if (err) { - res.writeHead(404); - res.end(JSON.stringify(err)); - return; - } - res.writeHead(200); - res.end(data); - }); - }).listen(8080); - -This example takes the path requested and it serves that path, relative to the local directory. This works fine as a quick solution; however, there are a few problems with this approach. First, this code does not correctly handle mime types. Additionally, a proper static file server should really be taking advantage of client side caching, and should send a "Not Modified" response if nothing has changed. Furthermore, there are security bugs that can enable a malicious user to break out of the current directory. (for example, `GET /../../../`). - -Each of these can be addressed invidually without much difficulty. You can send the proper mime type header. You can figure how to utilize the client caches. You can take advantage of `path.normalize` to make sure that requests don't break out of the current directory. But why write all that code when you can just use someone else's library? - -There is a good static file server called [node-static](https://github.com/cloudhead/node-static) written by Alexis Sellier which you can leverage. Here is a script which functions similarly to the previous one: - - var static = require('node-static'); - var http = require('http'); - - var file = new(static.Server)(); - - http.createServer(function (req, res) { - file.serve(req, res); - }).listen(8080); - -This is a fully functional file server that doesn't have any of the bugs previously mentioned. This is just the most basic set up, there are more things you can do if you look at [the api](https://github.com/cloudhead/node-static). Also since it is an open source project, you can always modify it to your needs (and feel free to contribute back to the project!). diff --git a/locale/uk/knowledge/REPL/how-to-create-a-custom-repl.md b/locale/uk/knowledge/REPL/how-to-create-a-custom-repl.md deleted file mode 100644 index 0f5642d888cb4..0000000000000 --- a/locale/uk/knowledge/REPL/how-to-create-a-custom-repl.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: How to create and use a custom REPL -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - repl -difficulty: 2 -layout: knowledge-post.hbs ---- - -Node allows users to create their own REPLs with the [repl module](https://nodejs.org/docs/v0.4.10/api/repl.html). Its basic use looks like this: - - repl.start(prompt, stream); - -`prompt` is a string that's used for the prompt of your REPL and defaults to "> ". `stream` is the stream that the repl listens on and defaults to `process.stdin`. When you run `node` from the command prompt, what it's doing in the background is running `repl.start()` to give you the standard REPL. - -However, the repl is pretty flexible. Here's an example that shows this off: - - #!/usr/bin/env node - - var net = require("net"), - repl = require("repl"); - - var mood = function () { - var 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); - - console.log("Remote REPL started on port 5001."); - - //A "local" node repl with a custom prompt - var local = repl.start("node::local> "); - - // Exposing the function "mood" to the local REPL's context. - local.context.mood = mood; - -This script creates *two* REPLs: One is normal excepting for its custom prompt, but the *other* is exposed via the net module so I can telnet to it! In addition, it uses the `context` property to expose the function "mood" to both REPLs, and the "bonus" string to the remote REPL only. As you will see, this approach of trying to expose objects to one REPL and not the other *doesn't really work*. - -In addition, all objects in the global scope will also be accessible to your REPLs. - -Here's what happens when I run the script: - - $ node repl.js - Remote REPL started on port 5001. - node::local> .exit - ^Cjosh@pidgey:/tmp/telnet$ node repl.js - Remote REPL started on port 5001. - node::local> mood() - '^__^' - node::local> bonus - ReferenceError: bonus is not defined - at [object Context]:1:1 - at Interface. (repl.js:171:22) - at Interface.emit (events.js:64:17) - at Interface._onLine (readline.js:153:10) - at Interface._line (readline.js:408:8) - at Interface._ttyWrite (readline.js:585:14) - at ReadStream. (readline.js:73:12) - at ReadStream.emit (events.js:81:20) - at ReadStream._emitKey (tty_posix.js:307:10) - at ReadStream.onData (tty_posix.js:70:12) - -As may be seen, the `mood` function is usable within the local REPL, but the -`bonus` string is not. This is as expected. - -Now, here's what happens when I try to telnet to port 5001: - - josh@pidgey:/tmp/telnet$ telnet localhost 5001 - Trying ::1... - Trying 127.0.0.1... - Connected to localhost. - Escape character is '^]'. - node::remote> mood() - '>.<' - node::remote> bonus - 'UNLOCKED' - -As you can see, the `mood` function is *also* available over telnet! In addition, so is "bonus". - -As an interesting consequence of my actions, bonus is now also defined on the local REPL: - - node::local> bonus - 'UNLOCKED' - -It seems we "unlocked" the `bonus` string on the local REPL as well. As it turns out, any variables created in one REPL are also available to the other: - - node::local> var node = "AWESOME!" - - node::remote> node - 'AWESOME!' - -As you can see, the node REPL is powerful and flexible. diff --git a/locale/uk/knowledge/REPL/how-to-use-nodejs-repl.md b/locale/uk/knowledge/REPL/how-to-use-nodejs-repl.md deleted file mode 100644 index 95faa01c126f0..0000000000000 --- a/locale/uk/knowledge/REPL/how-to-use-nodejs-repl.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: "How do I use node's REPL?" -date: '2011-08-26T10:08:50.000Z' -tags: - - cli - - repl -difficulty: 1 -layout: knowledge-post.hbs ---- - -Node.js ships with a REPL, which is short for 'Read-Eval-Print Loop'. It is the Node.js shell; any valid JavaScript which can be written in a script can be passed to the REPL. It can be extremely useful for experimenting with node.js, debugging code, and figuring out some of JavaScript's more eccentric behaviors. - -Running it is simple - just run node without a filename. - - docs@nodejitsu:~/$ node - -It then drops you into a simple prompt ('>') where you can type any JavaScript command you wish. As in most shells, you can press the up and down arrow keys to scroll through your command history and modify previous commands. The REPL also `Tab` to make the REPL try to autocomplete the command. - -Whenever you type a command, it will print the return value of the command. If you want to reuse the previous return value, you can use the special `_` variable. - -For example: - - node - > 1+1 - 2 - > _+1 - 3 - -One thing worth noting where REPL return values are concerned: - - > x = 10 - 10 - > var y = 5 - > x - 10 - > y - 5 - -When the `var` keyword is used, the value of the expression is stored, but *NOT* returned. When a bare identifier is used, the value is also returned, as well as stored. - -If you need to access any of the builtin modules, or any third party modules, they can be accessed with `require`, just like in the rest of Node. - -For example: - - node - > path = require('path') - { resolve: [Function], - normalize: [Function], - join: [Function], - dirname: [Function], - basename: [Function], - extname: [Function], - exists: [Function], - existsSync: [Function] } - > path.basename("/a/b/c.txt") - 'c.txt' - -Note once again that without the `var` keyword, the contents of the object are returned immediately and displayed to `stdout`. diff --git a/locale/uk/knowledge/advanced/buffers/how-to-use-buffers.md b/locale/uk/knowledge/advanced/buffers/how-to-use-buffers.md deleted file mode 100644 index 2660e5d56e0de..0000000000000 --- a/locale/uk/knowledge/advanced/buffers/how-to-use-buffers.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: How to Use Buffers in Node.js -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - Buffer - - buffer - - buffers - - binary -difficulty: 3 -layout: knowledge-post.hbs ---- - -## Why Buffers? - -Pure javascript, while great with unicode-encoded strings, does not handle straight binary data very well. This is fine on the browser, where most data is in the form of strings. However, node.js servers have to also deal with TCP streams and reading and writing to the filesystem, both which make it necessary to deal with purely binary streams of data. - -One way to handle this problem is to just use strings *anyway*, which is exactly what Node.js did at first. However, this approach is extremely problematic to work with; It's slow, makes you work with an API designed for strings and not binary data, and has a tendency to break in strange and mysterious ways. - -Don't use binary strings. Use *buffers* instead! - -## What Are Buffers? - -Buffers are instances of the `Buffer` class in node, which is designed to handle raw binary data. Each buffer corresponds to some raw memory allocated outside V8. Buffers act somewhat like arrays of integers, but aren't resizable and have a whole bunch of methods specifically for binary data. In addition, the "integers" in a buffer each represent a byte and so are limited to values from 0 to 255 (2^8 - 1), inclusive. - -## Where You See Buffers: - -In the wild, buffers are usually seen in the context of binary data coming from streams, such as `fs.createReadStream`. - -## Usage: - -### Creating Buffers: - -There are a few ways to create new buffers: - - var buffer = new Buffer(8); - -This buffer is uninitialized and contains 8 bytes. - - var buffer = new Buffer([ 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. - - var buffer = new Buffer("I'm a string!", "utf-8") - -This initializes the buffer to a binary encoding of the first string as specified by the second argument (in this case, utf-8). **utf-8** is by far the most common encoding used with node, but `Buffer` also supports: - -* **"ascii"**: This encoding is way fast, but is limited to the ascii character set. Moreover, it will convert null characters into spaces, unlike the utf-8 encoding. -* **"ucs2"**: A two-byte, little-endian encoding. Can encode a subset of unicode. -* **"base64"**: Base64 string encoding. -* **"binary"**: This is the "binary string" format mentioned earlier, and is in the process of being deprecated. Avoid its use. - -### Writing to Buffers - -Given that there is already a buffer created: - - > var buffer = new Buffer(16); - -we can start writing strings to it: - - > buffer.write("Hello", "utf-8") - 5 - -The first argument to `buffer.write` is the string to write to the buffer, and the second argument is the string encoding. It happens to default to utf-8 so this argument is extraneous. - -`buffer.write` returned 5. This means that we wrote to five bytes of the buffer. The fact that the string "Hello" is also 5 characters long is coincidental, since each character *just happened* to be 8 bits apiece. This is useful if you want to complete the message: - - > buffer.write(" world!", 5, "utf-8") - 7 - -When `buffer.write` has 3 arguments, the second argument indicates an offset, or the index of the buffer to start writing at. - -### Reading from Buffers: - -#### toString: - -Probably the most common way to read buffers is to use the `toString` method, since many buffers contain text: - - > buffer.toString('utf-8') - 'Hello world!\u0000�k\t' - -Again, the first argument is the encoding. In this case, it can be seen that not the entire buffer was used! Luckily, because we know how many bytes we've written to the buffer, we can simply add more arguments to "stringify" the slice that's actually interesting: - - > buffer.toString("utf-8", 0, 12) - 'Hello world!' - -#### Individual octets: - -You can also set individual bytes by using an array-like syntax: - - > buffer[12] = buffer[11]; - 33 - > buffer[13] = "1".charCodeAt(); - 49 - > buffer[14] = buffer[13]; - 49 - > buffer[15] = 33 - 33 - > buffer.toString("utf-8") - 'Hello world!!11!' - -In this example, I set the remaining bytes, by hand, such that they represent utf-8 encoded "!" and "1" characters. - -### More Fun With Buffers - -#### Buffer.isBuffer(object) - -This method checks to see if `object` is a buffer, similar to `Array.isArray`. - -#### Buffer.byteLength(string, encoding) - -With this function, you can check the number of bytes required to encode a string with a given encoding (which defaults to utf-8). This length is *not* the same as string length, since many characters require more bytes to encode. For example: - - > var snowman = "☃"; - > snowman.length - 1 - > Buffer.byteLength(snowman) - 3 - -The unicode snowman is only one character, but takes 3 entire bytes to encode! - -#### buffer.length - -This is the length of your buffer, and represents how much memory is allocated. It is not the same as the size of the buffer's contents, since a buffer may be half-filled. For example: - - > var buffer = new Buffer(16) - > buffer.write(snowman) - 3 - > buffer.length - 16 - -In this example, the contents written to the buffer only consist of three groups (since they represent the single-character snowman), but the buffer's length is still 16, as it was initialized. - -#### buffer.copy(target, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - -`buffer.copy` allows one to copy the contents of one buffer onto another. The first argument is the target buffer on which to copy the contents of `buffer`, and the rest of the arguments allow for copying only a subsection of the source buffer to somewhere in the middle of the target buffer. For example: - - > var frosty = new Buffer(24) - > var snowman = new Buffer("☃", "utf-8") - > frosty.write("Happy birthday! ", "utf-8") - 16 - > snowman.copy(frosty, 16) - 3 - > frosty.toString("utf-8", 0, 19) - 'Happy birthday! ☃' - -In this example, I copied the "snowman" buffer, which contains a 3 byte long character, to the "frosty" buffer, to which I had written to the first 16 bytes. Because the snowman character is 3 bytes long, the result takes up 19 bytes of the buffer. - -#### buffer.slice(start, end=buffer.length) - -This method's API is generally the same as that of `Array.prototype.slice`, but with one very import difference: The slice is **not** a new buffer and merely references a subset of the memory space. *Modifying the slice will also modify the original buffer*! For example: - - > var puddle = frosty.slice(16, 19) - > puddle.toString() - '☃' - > puddle.write("___") - 3 - > frosty.toString("utf-8", 0, 19) - 'Happy birthday! ___' - -Now Frosty has been turned into a puddle of underscores. Bummer. diff --git a/locale/uk/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md b/locale/uk/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md deleted file mode 100644 index db4464bad2168..0000000000000 --- a/locale/uk/knowledge/advanced/streams/how-to-use-fs-create-read-stream.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: How to use fs.createReadStream? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - streams - - fs -difficulty: 3 -layout: knowledge-post.hbs ---- - -The function `fs.createReadStream()` allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams. So we will use this fact to create a http server that streams the files to the client. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary. - - var http = require('http'); - var fs = require('fs'); - - http.createServer(function(req, res) { - // The filename is simple the local directory and tacks on the requested url - var filename = __dirname+req.url; - - // This line opens the file as a readable stream - var readStream = fs.createReadStream(filename); - - // This will wait until we know the readable stream is actually valid before piping - readStream.on('open', function () { - // This just pipes the read stream to the response object (which goes to the client) - readStream.pipe(res); - }); - - // This catches any errors that happen while creating the readable stream (usually invalid names) - readStream.on('error', function(err) { - res.end(err); - }); - }).listen(8080); diff --git a/locale/uk/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md b/locale/uk/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md deleted file mode 100644 index 8c678f854fc76..0000000000000 --- a/locale/uk/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: How to use fs.createWriteStream? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - streams - - fs -difficulty: 3 -layout: knowledge-post.hbs ---- - -The function `fs.createWriteStream()` creates a writable stream in a very simple manner. After a call to `fs.createWriteStream` with the filepath, you have a writeable stream to work with. It turns out that the response (as well as the request) objects are streams. So we will stream the `POST` data to the file `output`. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary. - - var http = require('http'); - var fs = require('fs'); - - http.createServer(function(req, res) { - // This opens up the writeable stream to `output` - var writeStream = fs.createWriteStream('./output'); - - // This pipes the POST data to the file - req.pipe(writeStream); - - // After all the data is saved, respond with a simple html form so they can post more data - req.on('end', function () { - res.writeHead(200, {"content-type":"text/html"}); - res.end('
'); - }); - - // This is here incase any errors occur - writeStream.on('error', function (err) { - console.log(err); - }); - }).listen(8080); diff --git a/locale/uk/knowledge/advanced/streams/how-to-use-stream-pipe.md b/locale/uk/knowledge/advanced/streams/how-to-use-stream-pipe.md deleted file mode 100644 index 8afdfccef5100..0000000000000 --- a/locale/uk/knowledge/advanced/streams/how-to-use-stream-pipe.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: How to use stream.pipe -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - streams -difficulty: 2 -layout: knowledge-post.hbs ---- - -If you've been using node.js for a while, you've definitely run into streams. HTTP connections are streams, open files are streams; stdin, stdout, and stderr are all streams as well. A 'stream' is node's I/O abstraction - if you feel like you still need to understand them better, you can read more about them [here](https://nodejs.org/api/stream.html#stream_stream). - -Streams make for quite a handy abstraction, and there's a lot you can do with them - as an example, let's take a look at stream.pipe, the method used to take a readable stream and connect it to a writeable steam. Suppose we wanted to spawn a `node` child process and pipe our stdout and stdin to its corresponding stdout and stdin. - - #!/usr/bin/env node - - var child = require('child_process'); - - var myREPL = child.spawn('node'); - - myREPL.stdout.pipe(process.stdout, { end: false }); - - process.stdin.resume(); - - process.stdin.pipe(myREPL.stdin, { end: false }); - - myREPL.stdin.on('end', function() { - process.stdout.write('REPL stream ended.'); - }); - - myREPL.on('exit', function (code) { - process.exit(code); - }); - -There you have it - spawn the node REPL as a child process, and pipe your stdin and stdout to its stdin and stdout. Make sure to listen for the child's 'exit' event, too, or else your program will just hang there when the REPL exits. - -Another use for stream.pipe is file streams. In node.js, fs.createReadStream and fs.createWriteStream are used to create a stream to an open file descriptor. Now let's look at how one might use stream.pipe to write to a file. You'll probably recognize most of the code: - - #!/usr/bin/env node - - var child = require('child_process'), - fs = require('fs'); - - var myREPL = child.spawn('node'), - myFile = fs.createWriteStream('myOutput.txt'); - - myREPL.stdout.pipe(process.stdout, { end: false }); - myREPL.stdout.pipe(myFile); - - process.stdin.resume(); - - process.stdin.pipe(myREPL.stdin, { end: false }); - process.stdin.pipe(myFile); - - myREPL.stdin.on("end", function() { - process.stdout.write("REPL stream ended."); - }); - - myREPL.on('exit', function (code) { - process.exit(code); - }); - -With those small additions, your stdin and the stdout from your REPL will both be piped to the writeable file stream you opened to 'myOutput.txt'. It's that simple - you can pipe streams to as many places as you want. - -Another very important use case for stream.pipe is with HTTP request and response objects. Here we have the very simplest kind of proxy: - - #!/usr/bin/env node - - var http = require('http'); - - http.createServer(function(request, response) { - var proxy = http.createClient(9000, 'localhost') - var proxyRequest = proxy.request(request.method, request.url, request.headers); - proxyRequest.on('response', function (proxyResponse) { - proxyResponse.pipe(response); - }); - request.pipe(proxyRequest); - }).listen(8080); - - http.createServer(function (req, res) { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2)); - res.end(); - }).listen(9000); - -One could also use stream.pipe to send incoming requests to a file for logging, or to a child process, or any one of a number of other things. - -Hopefully this has shown you the basics of using stream.pipe to easily pass your data streams around. It's truly a powerful little trick in node.js, and its uses are yours to explore. Happy coding, and try not to cross your streams! diff --git a/locale/uk/knowledge/advanced/streams/what-are-streams.md b/locale/uk/knowledge/advanced/streams/what-are-streams.md deleted file mode 100644 index 6380a79ea20fe..0000000000000 --- a/locale/uk/knowledge/advanced/streams/what-are-streams.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: What are streams? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - streams -difficulty: 3 -layout: knowledge-post.hbs ---- - -Streams are another basic construct in node.js that encourages asynchronous coding. Streams allow you to process the data as it is generated or retrieved. Streams can be readable, writeable, or both. - -In other words, Streams use events to deal with data as it happens, rather than only with a callback at the end. Readable streams emit the event `data` for each chunk of data that comes in, and an `end` event, which is emitted when there is no more data. Writeable streams can be written to with the `write()` function, and closed with the `end()` function. All types of streams emit `error` events when errors arise. - -As a quick example, we can write a simple version of `cp` (the unix utility that copies files). We could do that by reading the whole file with standard filesystem calls and then writing it out to a file. Unfortunately, that requires that the whole file be read in before it can be written. In the case of 1-2 giga files, you could run into out of memory operations. The biggest advantage that streams give you over their non-stream versions are that you can start process the info before you have all the information. In this case, writing out the file doesn't get sped up, but if we were streaming over the internet or doing cpu processing on it then there could be measurable performance improvements. - -Run this script with arguments like `node cp.js src.txt dest.txt`. This would mean, in the code below, that `process.argv[2]` is `src.txt` and `process.argv[3]` is `desc.txt`. - - var fs = require('fs'); - console.log(process.argv[2], '->', process.argv[3]); - - var readStream = fs.createReadStream(process.argv[2]); - var writeStream = fs.createWriteStream(process.argv[3]); - - readStream.on('data', function (chunk) { - writeStream.write(chunk); - }); - - readStream.on('end', function () { - writeStream.end(); - }); - - //Some basic error handling - readStream.on('error', function (err) { - console.log("ERROR", err); - }); - - writeStream.on('error', function (err) { - console.log("ERROR", err); - }); - -This sets up a readable stream from the source file and a writable stream to the destination file. Then whenever the readable stream gets data, it gets written to the writeable stream. Then finally it closes the writable stream when the readable stream is finished. NOTE: it would have been better to use [pipe](/how-to-use-stream-pipe) like `readStream.pipe(writeStream);`, however, to show how streams work, we have done things the long way. diff --git a/locale/uk/knowledge/child-processes/how-to-spawn-a-child-process.md b/locale/uk/knowledge/child-processes/how-to-spawn-a-child-process.md deleted file mode 100644 index fb05d9b25dc71..0000000000000 --- a/locale/uk/knowledge/child-processes/how-to-spawn-a-child-process.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: How to spawn a child process - the basics -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - child_process -difficulty: 2 -layout: knowledge-post.hbs ---- - -If you find yourself wishing you could have your Node.js process start another program for you, then look no further than the `child_process` module. - -The simplest way is the "fire, forget, and buffer" method using `child_process.exec`. It runs your process, buffers its output (up to a default maximum of 200kb), and lets you access it from a callback when it is finished. Let us take a look at an example: - - var childProcess = require('child_process'), - ls; - - ls = childProcess.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('Child Process STDOUT: '+stdout); - console.log('Child Process STDERR: '+stderr); - }); - - ls.on('exit', function (code) { - console.log('Child process exited with exit code '+code); - }); - -NODE PRO TIP: `error.stack` is a stack trace to the point that the [Error object](/what-is-the-error-object) was created. - -It should be noted that the `STDERR` of a given process is not exclusively reserved for error messages. Many programs use it as a channel for secondary data instead. As such, when trying to work with a program that you have not previously spawned as a child process, it can be helpful to start out dumping both `STDOUT` and `STDERR`, as shown above, to avoid any surprises. - -While `child_process.exec` buffers the output of the child process for you, it also returns a `ChildProcess` object, Node's way of wrapping a still-running process. In the example above, since we are using `ls`, a program that will exit immediately regardless, the only part of the `ChildProcess` object worth worrying about is the `on exit` handler. It is not necessary here - the process will still exit and the error code will still be shown on errors. diff --git a/locale/uk/knowledge/command-line/how-to-get-colors-on-the-command-line.md b/locale/uk/knowledge/command-line/how-to-get-colors-on-the-command-line.md deleted file mode 100644 index 68a42ef5e5cd1..0000000000000 --- a/locale/uk/knowledge/command-line/how-to-get-colors-on-the-command-line.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: How to get colors on the command line -date: '2011-08-26T10:08:50.000Z' -tags: - - cli -difficulty: 1 -layout: knowledge-post.hbs ---- - -When working on the command line, it can be both fun and extremely useful to colorize one's output. To colorize console output, you need to use ANSI escape codes. The module `colors.js`, available on `npm`, provides an extremely easy to use wrapper that makes adding colors a breeze. - -First, install it to the directory you'd like to work in. - - cd mydir - npm install colors - -Now open up a little test script for yourself, and try something like this: - - var colors = require('colors'), - stringOne = 'This is a plain string.', - stringTwo = 'This string is red.'.red, - stringThree = 'This string is blue.'.blue; - - console.log(stringOne.green); - console.log(stringOne.yellow); - - console.log(stringTwo); - console.log(stringThree); - - console.log(stringTwo.magenta); - console.log(stringThree.grey.bold); - -There are several things to take note of here - first, the string object has been prototyped, so any color may be added simply by adding the property to the string! It works both on string literals and on variables, as shown at the top of the example above. - -Notice, also, from the second pair of `console.log` statements, that once set, a color value persists as part of the string. This is because under the hood, the proper ANSI color tags have been prepended and appended as necessary - anywhere the string gets passed where ANSI color codes are also supported, the color will remain. - -The last pair of `console.log` statements are probably the most important. Because of the way `colors.js` and ANSI color codes work, if more than one color property is set on a string, **only the first color property to be set on the string takes effect.** This is because the colors function as 'state shifts' rather than as tags. - -Let's look at a more explicit example. If you set the following properties with `colors.js`: - - 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). - -The last thing to note is the final line of the example script. While a color code was set previously, a 'bold' code was not, so the example was made bold, but not given a different color. - -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! - -For reference, here's the full list of available `colors.js` properties. - -- bold -- italic -- underline -- inverse -- yellow -- cyan -- white -- magenta -- green -- red -- grey -- blue -- rainbow - -Some people may tell you that `colors.js` is haunted, but those people are just trolls... right? diff --git a/locale/uk/knowledge/command-line/how-to-parse-command-line-arguments.md b/locale/uk/knowledge/command-line/how-to-parse-command-line-arguments.md deleted file mode 100644 index bd8a97941ed0a..0000000000000 --- a/locale/uk/knowledge/command-line/how-to-parse-command-line-arguments.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: How to parse command line arguments -date: '2011-08-26T10:08:50.000Z' -tags: - - cli -difficulty: 1 -layout: knowledge-post.hbs ---- - -Passing in arguments via the command line is an extremely basic programming task, and a necessity for anyone trying to write a simple Command-Line Interface (CLI). In Node.js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called `argv` (short for 'argument values'). - -Node.js exposes this array for every running process in the form of `process.argv` - let's take a look at an example. Make a file called `argv.js` and add this line: - - console.log(process.argv); - -Now save it, and try the following in your shell: - - $ node argv.js one two three four five - [ 'node', - '/home/avian/argvdemo/argv.js', - 'one', - 'two', - 'three', - 'four', - 'five' ] - -There you have it - an array containing any arguments you passed in. Notice the first two elements - `node` and the path to your script. These will always be present - even if your program takes no arguments of its own, your script's interpreter and path are still considered arguments to the shell you're using. - -Where everyday CLI arguments are concerned, you'll want to skip the first two. Now try this in `argv.js`: - - var myArgs = process.argv.slice(2); - console.log('myArgs: ', myArgs); - -This yields: - - $ node argv.js one two three four - myArgs: [ 'one', 'two', 'three', 'four' ] - -Now let's actually do something with the args: - - var myArgs = process.argv.slice(2); - console.log('myArgs: ', myArgs); - - switch (myArgs[0]) { - case 'insult': - console.log(myArgs[1], 'smells quite badly.'); - break; - case 'compliment': - console.log(myArgs[1], 'is really cool.'); - break; - default: - console.log('Sorry, that is not something I know how to do.'); - } - -JS PRO TIP: Remember to `break` after each `case` - otherwise you'll run the next case too! - -Referring to your command-line arguments by array index isn't very clean, and can quickly turn into a nightmare when you start working with flags and the like - imagine you made a server, and it needed a lot of arguments. Imagine having to deal with something like `myapp -h host -p port -r -v -b --quiet -x -o outfile` - some flags need to know about what comes next, some don't, and most CLIs let users specify arguments in any order they want. Sound like a fun string to parse? - -Luckily, there's a third party module that makes all of this trivial - it's called [Optimist](https://github.com/substack/node-optimist), written by one Mr. James Halliday (aka SubStack). It's available via `npm`. Use this command from your app's base path: - - npm install optimist - -Once you have it, give it a try - it can really be a life-saver. - - var myArgs = require('optimist').argv, - help = 'This would be a great place for real help information.'; - - if ((myArgs.h)||(myArgs.help)) { - console.log(help); - process.exit(0); - } - - switch (myArgs._[0]) { - case 'insult': - console.log(myArgs.n || myArgs.name, 'smells quite badly.'); - break; - case 'compliment': - console.log(myArgs.n || myArgs.name, 'is really cool.'); - break; - default: - console.log(help); - } - - console.log('myArgs: ', myArgs); - -The last line was included to let you see how Optimist handles your arguments. Here's a quick reference: - -- `argv.$0` contains the first two elements of `process.argv` joined together - "node ./myapp.js". -- `argv._` is an array containing each element not attached to a flag. -- Individual flags become properties of `argv`, such as with `myArgs.h` and `myArgs.help`. Note that non-single-letter flags must be passed in as `--flag`. - -For more information on Optimist and the many, many other things it can do for your command-line arguments, please visit [https://github.com/substack/node-optimist](https://github.com/substack/node-optimist) diff --git a/locale/uk/knowledge/command-line/how-to-prompt-for-command-line-input.md b/locale/uk/knowledge/command-line/how-to-prompt-for-command-line-input.md deleted file mode 100644 index 6ec44e670f124..0000000000000 --- a/locale/uk/knowledge/command-line/how-to-prompt-for-command-line-input.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: How do I prompt users for input from a command-line script? -date: '2011-08-26T10:08:50.000Z' -tags: - - javascript - - core - - cli -difficulty: 2 -layout: knowledge-post.hbs ---- - -So you've got a little CLI tool, but you want to be able to prompt a user for additional data after the script has started, rather than passing it in as a command line argument or putting it in a file. To do this, you'll need to listen to STDIN ("standard input", i.e. your keyboard), which Node.js exposes for you as `process.stdin`, a readable stream. - -Streams are Node's way of dealing with evented I/O - they're a big topic, and you can read more about them (here). For now, we're only going to deal with the Stream methods relevant to working with `process.stdin` so as to keep the examples easy. - -The first two Readable Stream methods you'll need to know about here are `pause()` and `resume()`. Not every program needs to care whether or not you're pressing keys at a given moment, so `process.stdin` is paused by default. - -Here's a simple example. Try the following in a new file: - - process.stdin.resume(); - process.stdin.setEncoding('utf8'); - var util = require('util'); - - process.stdin.on('data', function (text) { - console.log('received data:', util.inspect(text)); - if (text === 'quit\n') { - done(); - } - }); - - function done() { - console.log('Now that process.stdin is paused, there is nothing more to do.'); - process.exit(); - } - -If all of this sounds complicated, or if you want a higher-level interface to this sort of thing, don't worry - as usual, the Node.js community has come to the rescue. One particularly friendly module to use for this is Prompt, maintained by Nodejitsu. It's available on `npm`: - - npm install prompt - -Prompt is built to be easy - if your eyes started to glaze over as soon as you saw `Readable Stream`, then this is the section for you. Compare the following to the example above: - - var 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); - }); - - function onErr(err) { - console.log(err); - return 1; - } - -NODE PRO TIP: This short script also demonstrates proper error handling in node - errors are a callback's first argument, and `return` is used with the error handler so that the rest of the function doesn't execute when errors happen. For more information, look (here). - -Prompt also makes it trivial to handle a certain set of recurring properties that one might want to attach. - - var prompt = require('prompt'); - - var properties = [ - { - 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); - }); - - function onErr(err) { - console.log(err); - return 1; - } - -For more information on Prompt, please see [the project's GitHub page](https://github.com/nodejitsu/node-prompt). diff --git a/locale/uk/knowledge/cryptography/how-to-use-crypto-module.md b/locale/uk/knowledge/cryptography/how-to-use-crypto-module.md deleted file mode 100644 index 8eeb40f3e713a..0000000000000 --- a/locale/uk/knowledge/cryptography/how-to-use-crypto-module.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: How to use the crypto module -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - crypto -difficulty: 3 -layout: knowledge-post.hbs ---- - -The [crypto](https://nodejs.org/docs/v0.4.10/api/crypto.html) module is a wrapper for [OpenSSL](https://en.wikipedia.org/wiki/Openssl) cryptographic functions. It supports calculating hashes, authentication with HMAC, ciphers, and more! - -The crypto module is mostly useful as a tool for implementing [cryptographic protocols](https://en.wikipedia.org/wiki/Cryptographic_protocol) such as [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security) and [https](https://en.wikipedia.org/wiki/Https). For most users, Node's built-in [tls module](https://nodejs.org/docs/v0.4.10/api/tls.html) and [https module](https://nodejs.org/docs/v0.4.10/api/https.html) should more than suffice. However, for the user that only wants to use small parts of what's needed for full-scale cryptography or is crazy/desperate enough to implement a protocol using OpenSSL and Node: Read on. - -## Hashes - -### What Is A Hash? - -A hash is a fixed-length string of bits that is procedurally and deterministially generated from some arbitrary block of source data. Some important properties of these hashes (the type useful for cryptography) include: - -* **Fixed length:** This means that, no matter what the input, the length of the hash is the same. For example, md5 hashes are always 128 bits long whether the input data is a few bits or a few gigabytes. - -* **Deterministic:** For the same input, you should expect to be able to calculate exactly the same hash. This makes hashes useful for checksums. - -* **Collision-Resistant:** A collision is when the same hash is generated for two different input blocks of data. Hash algorithms are designed to be extremely unlikely to have collisions -- just how unlikely is a property of the hash algorithm. The importance of this property depends on the use case. - -* **Unidirectional:** A good hash algorithm is easy to apply, but hard to undo. This means that, given a hash, there isn't any reasonable way to find out what the original piece of data was. - -### Hash Algorithms That Work With Crypto - -The hashes that work with crypto are dependent on what your version of OpenSSL supports. If you have a new enough version of OpenSSL, you can get a list of hash types your OpenSSL supports by typing `openssl list-message-digest-algorithms` into the command line. For older versions, simply type `openssl list-message-digest-commands` instead! Some of the most common hash types are: - -* [sha1](https://en.wikipedia.org/wiki/Sha1) -* [md5](https://en.wikipedia.org/wiki/Md5). - -### How To Calculate Hashes with Crypto - -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 md5 hash for the string, "Man oh man do I love node!": - - require("crypto") - .createHash("md5") - .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. - -## HMAC - -HMAC stands for Hash-based Message Authentication Code, and is a process for applying a hash algorithm to both data and a secret key that results in a single final hash. Its use is similar to that of a vanilla hash, but also allows to check the *authenticity* of data as *well* as the integrity of said data (as you can using md5 checksums). - -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: - - require("crypto").createHmac("md5", "password") - .update("If you love node so much why don't you marry it?") - .digest("hex"); - -The resulting md5 hash is unique to both the input data and the key. - -## Ciphers - -Ciphers allow you to encode and decode messages given a password. - -### Cipher Algorithms That Work With Crypto - -Like crypto's hash algorithms, the cyphers that work with crypto are dependent on what your version of OpenSSL supports. You can get a list of hash types your OpenSSL supports by typing `openssl list-cipher-commands` into the command line for older versions, or `openssl list-cipher-algorithms` for newer versions of OpenSSL. OpenSSL supports *many* ciphers; A good and popular one is [AES192](https://en.wikipedia.org/wiki/Aes192). - -### How To Use Cipher Algorithms with Crypto: - -Crypto comes with two methods for ciphering and deciphering: - -* `crypto.createCypher(algorithm, key)` -* `crypto.createDecipher(algorithm, key)` - -Both of these methods take arguments similarly to `createHmac`. They also both have analogous `update` functions. However, each use of `update` returns a chunk of the encoded/decoded data instead of requiring one to call `digest` to get the result. Moreover, after encoding (or decoding) your data, you will likely have to call the `final` method to get the last chunk of encoded information. - -Here's an example, slightly less trivial than previous examples, that uses crypto and [optimist](https://github.com/substack/node-optimist) to encode and decode messages from the command line: - - #!/usr/bin/env node - - var crypto = require("crypto"), - argv = require("optimist").argv; - - if (argv.e && argv.password) { - var cipher = crypto.createCipher("aes192", argv.password), - msg = []; - - 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.password) { - var decipher = crypto.createDecipher("aes192", argv.password), - msg = []; - - argv._.forEach( function (phrase) { - msg.push(decipher.update(phrase, "hex", "binary")); - }); - - msg.push(decipher.final("binary")); - console.log(msg.join("")); - } - -Using this script to encode a message looks like this: - - $ ./secretmsg.js -e --password="popcorn" "My treasure is buried behind Carl's Jr. on Telegraph." - 6df66752b24f0886f8a6c55e56977788c2090bb657ff3bd645097f8abe11099963fb3bd9627986c60fa7e5120d8fead928cff620b37e3e79be8de519f490527a - -Now, if I gave somebody the same script, my encoded message and the password, they can decode the message and find out where I buried my treasure: - - $ ./secretmsg.js -d --password="popcorn" 6df66752b24f0886f8a6c55e56977788c2090bb657ff3bd645097f8abe11099963fb3bd9627986c60fa7e5120d8fead928cff620b37e3e79be8de519f490527a - My treasure is buried behind Carl's Jr. on Telegraph. - -You should know that what I buried behind Carl's Jr was just a cigarette butt, and that this script is obviously not for serious use. - -## Signing and Verification - -Crypto has other methods used for dealing with certificates and credentials, as used for TLS: - -* `crypto.createCredentials` -* `crypto.createSign` -* `crypto.createVerify` - -These methods supply the last building blocks for a complete cryptographic protocol, and require an advanced knowledge of real-world cryptographic protocols to be useful. Again, it is recommended that developers use either the [tls](https://nodejs.org/docs/v0.4.10/api/tls.html) module or the [https](https://nodejs.org/docs/v0.4.10/api/https.html) module if applicable. diff --git a/locale/uk/knowledge/cryptography/how-to-use-the-tls-module.md b/locale/uk/knowledge/cryptography/how-to-use-the-tls-module.md deleted file mode 100644 index 75fd666e9d7ef..0000000000000 --- a/locale/uk/knowledge/cryptography/how-to-use-the-tls-module.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: How To Use The TLS Module -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - tls - - ssl - - secure -difficulty: 3 -layout: knowledge-post.hbs ---- - -## What is TLS? - -[Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) (or TSL) is the successor to Secure Sockets Layer (or SSL). It, along with SSL, are the de-facto standard cryptographic protocols for secure communications over the web. TSL encrypts communications on top of a network transport layer (typically tcp), and uses public-key cryptography to encrypt messages. - -### Public-Key Cryptography - -In public-key cryptography, each peer has two keys: A public key, and a private key. The public key is shared with everyone, and the private key is (naturally) kept secret. In order to encrypt a message, a computer requires its private key and the recipient's public key. Then, in order to decrypt the message, the recipient requires its *own* private key and the *sender*'s public key. - -In TLS connections, the public key is called a *[certificate](https://en.wikipedia.org/wiki/Digital_certificate)*. This is because it's "[signed](https://en.wikipedia.org/wiki/Digital_signature)" to prove that the public key belongs to its owner. TLS certificates may either be signed by a third-party certificate authority (CA), or they may be [self-signed](https://en.wikipedia.org/wiki/Self-signed_certificate). In the case of Certificate Authorities, Mozilla keeps [a list of trusted root CAs](http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt) that are generally agreed upon by most web browsers. These root CAs may then issue certificates to other signing authorities, which in turn sign certificates for the general public. - -### History of TLS/SSL Support in Node.JS - -TLS support in node is relatively new. The first stable version of node.js to support TSL and HTTPS was the v0.4 branch, which was released in early 2011. Since then, the primary focus of the core developers has shifted from TLS/HTTPS to Windows support in the v0.5 branch. As such, the TSL APIs in node are still a little rough around the edges, and documentation leaves something to be desired. - -## The tls Module - -### tls.createServer - -In most ways, the tls module's server api is similar to that of the net module. Besides the fact that it's for encrypted connections, the major difference is that the options object passed to `tls.connect` or `tls.createServer` needs to include information on both the private key and the certificate, in [pem format](https://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions). Here's an example of a tls server: - - var tls = require('tls'), - fs = require('fs'), - colors = require('colors'), - msg = [ - ".-..-..-. .-. .-. .--. .---. .-. .---. .-.", - ": :; :: : : :.-.: :: ,. :: .; :: : : . :: :", - ": :: : : :: :: :: :: :: .': : : :: :: :", - ": :: :: : : `' `' ;: :; :: :.`.: :__ : :; ::_;", - ":_;:_;:_; `.,`.,' `.__.':_;:_;:___.':___.':_;" - ].join("\n").cyan; - - var options = { - key: fs.readFileSync('private-key.pem'), - cert: fs.readFileSync('public-cert.pem') - }; - - tls.createServer(options, function (s) { - s.write(msg+"\n"); - s.pipe(s); - }).listen(8000); - -In this example, a "hello world" tls server is created, listening on port 8000. The options object includes two properties: `key` and `cert`. The contents of these properties come directly from the private key and public certificate stored on the filesystem. In this case they are binary buffers, but the tls module can also accept unicode strings. - -### Generating Your Private Key And Certificate With OpenSSL: - -In order for this example server to work, of course, you will need a private key and a certificate. You can generate both of these with OpenSSL. - -First, generate a private key: - - $ openssl genrsa -out private-key.pem 1024 - Generating RSA private key, 1024 bit long modulus - ......................................++++++ - ........++++++ - e is 65537 (0x10001) - -This creates a suitable private key and writes it to `./private-key.pem`. - -Next, create a Certificate Signing Request file using your private key: - - $ openssl req -new -key private-key.pem -out csr.pem - You are about to be asked to enter information that will be incorporated - into your certificate request. - What you are about to enter is what is called a Distinguished Name or a DN. - There are quite a few fields but you can leave some blank - For some fields there will be a default value, - If you enter '.', the field will be left blank. - ----- - Country Name (2 letter code) [AU]:US - State or Province Name (full name) [Some-State]:California - Locality Name (eg, city) []:Oakland - Organization Name (eg, company) [Internet Widgits Pty Ltd]:Panco, Inc. - Organizational Unit Name (eg, section) []: - Common Name (eg, YOUR name) []:Joshua Holbrook - Email Address []:josh.holbrook@gmail.com - - Please enter the following 'extra' attributes - to be sent with your certificate request - A challenge password []:dangerface - An optional company name []: - -The purpose of this CSR is to "request" a certificate. That is, if you wanted a CA to sign your certificate, you could give this file to them to process and they would give you back a certificate. - -Alternately, however, you may self-sign your certificate, again using your private key: - - $ openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem - Signature ok - subject=/C=US/ST=California/L=Oakland/O=Panco, Inc./CN=Joshua Holbrook/emailAddress=josh.holbrook@gmail.com - Getting Private key - -This generates your certificate. Now you're cooking! - -### Trying it out: - -One way to test out your new "hello world" server is to again use OpenSSL: - - openssl s_client -connect 127.0.0.1:8000 - -You should see a bunch of output regarding the handshaking process, and then at the very end you should see a big, cyan figlet banner saying, "Hi world!" - -### tls.connect - -The tls module also supplies tools for connecting to such a server: - - var tls = require('tls'), - fs = require('fs'); - - var options = { - key: fs.readFileSync('private-key.pem'), - cert: fs.readFileSync('public-cert.pem') - }; - - var conn = tls.connect(8000, options, function() { - if (conn.authorized) { - console.log("Connection authorized by a Certificate Authority."); - } else { - console.log("Connection not authorized: " + conn.authorizationError) - } - console.log(); - }); - - conn.on("data", function (data) { - console.log(data.toString()); - conn.end(); - }); - -The idea is similar, except instead of creating a server, this script connects to one instead. `tls.connect` also takes an options object, but then returns a stream. - -`tls.connect` also fires a callback when the connection is made, which allows for checking to see if the connection is authorized---that is, if all the certificates are in order. `conn.authorized` is a boolean, and `conn.authorizationError` is a string containing the reason that the connection is unauthorized. - -This is what happens when the client is ran (with the server running): - - $ node client.js - Connection not authorized: DEPTH_ZERO_SELF_SIGNED_CERT - - .-..-..-. .-. .-. .--. .---. .-. .---. .-. - : :; :: : : :.-.: :: ,. :: .; :: : : . :: : - : :: : : :: :: :: :: :: .': : : :: :: : - : :: :: : : `' `' ;: :; :: :.`.: :__ : :; ::_; - :_;:_;:_; `.,`.,' `.__.':_;:_;:___.':___.':_; - -Note that self-signing the server certificate results in a non-authorized status because you're not listed as a trusted certificate authority. - -## "starttls" - -It's entirely possible to "upgrade" an existing tcp connection into a TLS-encrypted one with node. However, node does not have a special functions for doing so as of the v0.4 branch. Therefore, it needs to be done "by-hand", using the crypto module and some undocumented tls module functionality. Node's documentation points to , which aims to abstract the process. diff --git a/locale/uk/knowledge/errors/what-are-the-error-conventions.md b/locale/uk/knowledge/errors/what-are-the-error-conventions.md deleted file mode 100644 index 9fd1a0666c4d2..0000000000000 --- a/locale/uk/knowledge/errors/what-are-the-error-conventions.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: What are the error conventions? -date: '2011-08-26T10:08:50.000Z' -tags: - - errors - - conventions -difficulty: 1 -layout: knowledge-post.hbs ---- - -In node.js, it is considered standard practice to handle errors in asynchronous functions by returning them as the first argument to the current function's callback. If there is an error, the first parameter is passed an `Error` object with all the details. Otherwise, the first parameter is null. - -It's simpler than it sounds; let's demonstrate. - - var isTrue = function(value, callback) { - if (value === true) { - callback(null, "Value was true."); - } - else { - callback(new Error("Value is not true!")); - } - } - - var callback = function (error, retval) { - if (error) { - console.log(error); - return; - } - console.log(retval); - } - - // Note: when calling the same asynchronous function twice like this, you are in a race condition. - // You have no way of knowing for certain which callback will be called first when calling the functions in this manner. - - isTrue(false, callback); - isTrue(true, callback); - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'Value is not true!' } - Value was true. - -As you can see from the example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an `Error` object, which then becomes the callback's only parameter. - -The `callback` function shows the reason for this: it allows a user to easily know whether or not an error occurred. If `null` was not the first argument passed on success, the user would need to check the object being returned and determine themselves whether or not the object constituted an error - a much more complex and less user-friendly approach. - -So to wrap it all up, when using callbacks, if an error comes up, then pass it as the first argument. Otherwise, pass `null` first, and then your return arguments. On the receiving end, inside the callback function, check if the first parameter is non-null; if it is, handle it as an error. diff --git a/locale/uk/knowledge/errors/what-is-the-error-object.md b/locale/uk/knowledge/errors/what-is-the-error-object.md deleted file mode 100644 index 0885ffc2a9953..0000000000000 --- a/locale/uk/knowledge/errors/what-is-the-error-object.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: What is the error object? -date: '2011-08-26T10:08:50.000Z' -tags: - - errors - - builtin -difficulty: 1 -layout: knowledge-post.hbs ---- - -The error object is a built-in object that provides a standard set of useful information when an error occurs, such as a stack trace and the error message. For example: - -Code: - - var error = new Error("The error message"); - console.log(error); - console.log(error.stack); - -Result: - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'The error message' } - Error: The error message - at Object. (/home/nico/example.js:1:75) - at Module._compile (module.js:407:26) - at Object..js (module.js:413:10) - at Module.load (module.js:339:31) - at Function._load (module.js:298:12) - at Array.0 (module.js:426:10) - at EventEmitter._tickCallback (node.js:126:26) - -`error.stack` shows you where an error came from, as well as a list of the function calls that preceded it - for your convenience, `error.stack` always prints `error.message` as the first line of its output, making `error.stack` a convenient single property to log during debugging. - -If you want to add more information to the Error object, you can always add properties, just as with any other JavaScript object: - - var error = new Error("The error message"); - error.http_code = 404; - console.log(error); - -For more details how to use the Error object, check out the [article on error conventions](/uk/knowledge/errors/what-are-the-error-conventions) diff --git a/locale/uk/knowledge/errors/what-is-try-catch.md b/locale/uk/knowledge/errors/what-is-try-catch.md deleted file mode 100644 index a7f33e9b11fba..0000000000000 --- a/locale/uk/knowledge/errors/what-is-try-catch.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: What is try-catch? -date: '2011-08-26T10:08:50.000Z' -tags: - - errors - - builtin -difficulty: 1 -layout: knowledge-post.hbs ---- - -Example: - - console.log("entering try-catch statement"); - - try { - console.log("entering try block"); - throw "thrown message"; - console.log("this message is never seen"); - } - catch (e) { - console.log("entering catch block"); - console.log(e); - console.log("leaving catch block"); - } - finally { - console.log("entering and leaving the finally block"); - } - - console.log("leaving try-catch statement"); - -Results: - - entering try-catch statement - entering try block - entering catch block - thrown message - leaving catch block - entering and leaving the finally block - leaving try-catch statement - -JavaScript's `try-catch-finally` statement works very similarly to the `try-catch-finally` encountered in C++ and Java. First, the try block is executed until and unless the code in it throws an exception (whether it is an explicit `throw` statement, the code has an uncaught native exception, or if the code calls a function that uses `throw`). - -If the code doesn't throw an exception, then the whole try block is executed. If the code threw an exception inside the try block, then the catch block is executed. Last of all, the finally block is always executed, subsequent to the other blocks but prior to any subsequent code located outside of the `try-catch-finally` blocks. The `finally` block will just about always execute, no matter what kind of throwing, catching, or returning one might be trying to do inside the `try` or `catch` blocks. - -Note that you can omit the `catch` or `finally` block, but one of them must be present. - -## But wait, isn't it Node.js convention to not use try-catch? - -In the core node.js libraries, the only place that one really *needs* to use a try-catch is around `JSON.parse()`. All of the other methods use either the standard Error object through the first parameter of the callback or emit an `error` event. Because of this, it is generally considered [standard](/what-are-the-error-conventions) to return errors through the callback rather than to use the `throw` statement. diff --git a/locale/uk/knowledge/file-system/how-to-read-files-in-nodejs.md b/locale/uk/knowledge/file-system/how-to-read-files-in-nodejs.md deleted file mode 100644 index 91864caf3d988..0000000000000 --- a/locale/uk/knowledge/file-system/how-to-read-files-in-nodejs.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: How do I read files in node.js? -date: '2011-08-26T10:08:50.000Z' -tags: - - filesystem -difficulty: 2 -layout: knowledge-post.hbs ---- - -Reading the contents of a file into memory is a very common programming task, and, as with many other things, the Node.js core API provides methods to make this trivial. There are a variety of file system methods, all contained in the `fs` module. The easiest way to read the entire contents of a file is with `fs.readFile`, as follows: - - fs = require('fs'); - fs.readFile(file, [encoding], [callback]); - - // file = (string) filepath of the file to read - -`encoding` is an optional parameter that specifies the type of encoding to read the file. Possible encodings are 'ascii', 'utf8', and 'base64'. If no encoding is provided, the default is `null`. - -`callback` is a function to call when the file has been read and the contents are ready - it is passed two arguments, `error` and `data`. If there is no error, `error` will be `null` and `data` will contain the file contents; otherwise `err` contains the error message. - -So if we wanted to read `/etc/hosts` and print it to stdout (just like UNIX `cat`): - - fs = require('fs') - fs.readFile('/etc/hosts', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); - -The contents of `/etc/hosts` should now be visible to you, provided you have permission to read the file in the first place. - -Let's now take a look at an example of what happens when you try to read an invalid file - the easiest example is one that doesn't exist. - - fs = require('fs'); - fs.readFile('/doesnt/exist', 'utf8', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); - -This is the output: - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'ENOENT, No such file or directory \'/doesnt/exist\'', - errno: 2, - code: 'ENOENT', - path: '/doesnt/exist' } - -This is a basic Node.js [Error object](/what-is-the-error-object) - it can often be useful to log `err.stack` directly, since this contains a stack trace to the location in code at which the Error object was created. diff --git a/locale/uk/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md b/locale/uk/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md deleted file mode 100644 index ea4225f60f86e..0000000000000 --- a/locale/uk/knowledge/file-system/how-to-search-files-and-directories-in-nodejs.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: How do I search files and directories? -date: '2011-08-26T10:08:50.000Z' -tags: - - filesystem -difficulty: 1 -layout: knowledge-post.hbs ---- - -Suppose you want to list all the files in the current directory. One approach is to use the builtin `fs.readdir` [method](/how-do-i-read-files-in-node-js). This will get you an array of all the files and directories on the specified path: - - fs = require('fs'); - - fs.readdir(process.cwd(), function (err, files) { - if (err) { - console.log(err); - return; - } - console.log(files); - }); - -Unfortunately, if you want to do a recursive list of files, then things get much more complicated very quickly. To avoid all of this scary complexity, this is one of the places where a Node.js user-land library can save the day. [Node-findit](https://github.com/substack/node-findit), by SubStack, is a helper module to make searching for files easier. It has interfaces to let you work with callbacks, events, or just plain old synchronously (not a good idea most of the time). - -To install `node-findit`, simply use npm: - - npm install findit - -In the same folder, create a file called `example.js`, and then add this code. Run it with `node example.js`. This example uses the `node-findit` event-based interface. - - //This sets up the file finder - var finder = require('findit').find(__dirname); - - //This listens for directories found - finder.on('directory', function (dir) { - console.log('Directory: ' + dir + '/'); - }); - - //This listens for files found - finder.on('file', function (file) { - console.log('File: ' + file); - }); diff --git a/locale/uk/knowledge/file-system/how-to-store-local-config-data.md b/locale/uk/knowledge/file-system/how-to-store-local-config-data.md deleted file mode 100644 index 52a298af08e5d..0000000000000 --- a/locale/uk/knowledge/file-system/how-to-store-local-config-data.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: How to store local configuration data -date: '2011-08-26T10:08:50.000Z' -tags: - - conventions - - filesystem -difficulty: 1 -layout: knowledge-post.hbs ---- - -Storing your Node.js application's configuration data is quite simple - every object in JavaScript can be easily rendered as [JSON](/what-is-json), which in turn is just string data that can be sent or saved any way you'd like. The simplest way to do this involves the built-in `JSON.parse()` and `JSON.stringify()` methods. - -Let's take a look at a very simple (and contrived) example. First, to save some very simple data: - - var fs = require('fs'); - - var myOptions = { - name: 'Avian', - dessert: 'cake' - flavor: 'chocolate', - beverage: 'coffee' - }; - - var data = JSON.stringify(myOptions); - - fs.writeFile('./config.json', data, function (err) { - if (err) { - console.log('There has been an error saving your configuration data.'); - console.log(err.message); - return; - } - console.log('Configuration saved successfully.') - }); - -It's really that simple - just `JSON.stringify()` and then save it however you'd like. - -Now let's load some configuration data: - - var fs = require('fs'); - - var data = fs.readFileSync('./config.json'), - myObj; - - try { - myObj = JSON.parse(data); - console.dir(myObj); - } - catch (err) { - console.log('There has been an error parsing your JSON.') - console.log(err); - } - -NODE PRO TIP: Even if you don't like using `try/catch`, this is a place to use it. `JSON.parse` is a very strict JSON parser, and errors are common - most importantly, though, `JSON.parse` uses the `throw` statement rather than giving a callback, so `try/catch` is the only way to guard against the error. - -Using the built-in `JSON` methods can take you far, but as with so many other problems you might be looking to solve with Node.js, there is already a solution in Userland that can take you much further. The solution, in this case, is `nconf`. Written by Charlie Robbins, it's a configuration manager for Node.js, supporting in-memory storage, local file storage, as well as support for a `redis` backend, provided in a separate module. - -Let's take a look now at how we'd perform some local configuration access with `nconf`. First, you'll need to install it to your project's working directory: - - npm install nconf - -After that, the syntax is a breeze. Have a look at an example: - - var nconf = require('nconf'); - - nconf.use('file', { file: './config.json' }); - nconf.load(); - nconf.set('name', 'Avian'); - nconf.set('dessert:name', 'Ice Cream'); - nconf.set('dessert:flavor', 'chocolate'); - - console.log(nconf.get('dessert')); - - nconf.save(function (err) { - if (err) { - console.error(err.message); - return; - } - console.log('Configuration saved successfully.'); - }); - -The only tricky thing to notice here is the delimiter - ':'. When accessing nested properties with `nconf`, a colon is used to delimit the namespaces of key names. If a specific sub-key is not provided, the whole object is set or returned. - -When using `nconf` to store your configuration data to a file, `nconf.save()` and `nconf.load()` are the only times that any actual file interaction will happen. All other access is performed on an in-memory copy of your data, which will not persist without a call to `nconf.save()`. Similarly, if you're trying to bring back configuration data from the last time your application ran, it will not exist in memory without a call to `nconf.load()`, as shown above. diff --git a/locale/uk/knowledge/file-system/how-to-use-the-path-module.md b/locale/uk/knowledge/file-system/how-to-use-the-path-module.md deleted file mode 100644 index b44ed0c7d8761..0000000000000 --- a/locale/uk/knowledge/file-system/how-to-use-the-path-module.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: How to use the path module? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - filesystem -difficulty: 1 -layout: knowledge-post.hbs ---- - -The path module contains several helper functions to help make path manipulation easier. - -The first function worth mentioning is `path.normalize`. This function takes a path (in the form of a string) and strips it of duplicate slashes and normalizes directory abbreviations, like '.' for 'this directory' and '..' for 'one level up'. For example: - - > var path = require('path'); - > path.normalize('/a/.///b/d/../c/') - '/a/b/c/' - -A closely related function to `normalize` is `join`. This function takes a variable number of arguments, joins them together, and normalizes the path. - - > var path = require('path'); - > path.join('/a/.', './//b/', 'd/../c/') - '/a/b/c' - -A possible use of `join` is to manipulate paths when serving urls: - - > var path = require('path'); - > var url = '/index.html'; - > path.join(process.cwd(), 'static', url); - '/home/nico/static/index.html' - -There are three functions which are used to extract the various parts of the path name: `basename`, `extname`, and `dirname`. -- `basename` returns the last portion of the path passed in. -- `extname` returns the extension of the last portion. Generally for directories, `extname` just returns ''. -- Finally, `dirname` returns everything that `basename` does not return. -For example: - - > var path = require('path') - > var a = '/a/b/c.html' - > path.basename(a) - 'c.html' - > path.extname(a) - '.html' - > path.dirname(a) - '/a/b' - -Note that `basename` has an optional second parameter that will strip out the extension if you pass the correct extension. - - > var path = require('path') - > var a = '/a/b/c.html' - > path.basename(a, path.extname(a)) - 'c' - -Lastly, the `path` module provides methods to check whether or not a given path exists: `exists` and `existsSync` They both take the path of a file for the first parameter. - -`exists` takes a callback as its second parameter, to which is returned a boolean representing the existence of the file. - -`existsSync`, on the other hand, checks the given path synchronously, returning the boolean directly. In Node.js, you will typically want to use the asynchronous functions for most file system I/O - the synchronous versions will block your entire process until they finish. - -Blocking isn't always a bad thing. Checking the existence of a vital configuration file synchronously makes sense, for example - it doesn't matter much if your process is blocking for something it can't run without! Conversely, though, in a busy HTTP server, any per-request file I/O **MUST** be asynchronous, or else you'll be responding to requests one by one. See the article on [asynchronous operations](/how-to-write-asynchronous-code) for more details. - - > var path = require('path') - > path.exists('/etc', function(exists){console.log("Does the file exist?", exists)}) - > Does the file exist? true - - > path.existsSync('/etc') - true diff --git a/locale/uk/knowledge/file-system/how-to-write-files-in-nodejs.md b/locale/uk/knowledge/file-system/how-to-write-files-in-nodejs.md deleted file mode 100644 index b45699d4d7883..0000000000000 --- a/locale/uk/knowledge/file-system/how-to-write-files-in-nodejs.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: How do I write files in node.js? -date: '2011-08-26T10:08:50.000Z' -tags: - - filesystem -difficulty: 2 -layout: knowledge-post.hbs ---- - -Writing to a file is another of the basic programming tasks that one usually needs to know about - luckily, this task is very simple in Node.js. We can use the handy `writeFile` method inside the standard library's `fs` module, which can save all sorts of time and trouble. - - fs = require('fs'); - fs.writeFile(filename, data, [encoding], [callback]) - -`file = (string)` filepath of the file to read - -`data = (string or buffer)` the data you want to write to the file - -`encoding = (optional string)` the encoding of the `data`. Possible encodings are 'ascii', 'utf8', and 'base64'. If no encoding provided, then 'utf8' is assumed. - -`callback = (optional function (err) {})` If there is no error, `err === null`, otherwise `err` contains the error message. - -So if we wanted to write "Hello World" to `helloworld.txt`: - - fs = require('fs'); - fs.writeFile('helloworld.txt', 'Hello World!', function (err) { - if (err) return console.log(err); - console.log('Hello World > helloworld.txt'); - }); - - [contents of helloworld.txt]: - Hello World! - -If we purposely want to cause an error, we can try to write to a file that we don't have permission to access: - - fs = require('fs') - fs.writeFile('/etc/doesntexist', 'abc', function (err,data) { - if (err) { - return console.log(err); - } - console.log(data); - }); - - { stack: [Getter/Setter], - arguments: undefined, - type: undefined, - message: 'EACCES, Permission denied \'/etc/doesntexist\'', - errno: 13, - code: 'EACCES', - path: '/etc/doesntexist' } diff --git a/locale/uk/knowledge/file-system/security/introduction.md b/locale/uk/knowledge/file-system/security/introduction.md deleted file mode 100644 index 8803a3e8964b4..0000000000000 --- a/locale/uk/knowledge/file-system/security/introduction.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: How can I secure my code? -date: null -tags: - - filesystem - - security -difficulty: 3 -layout: knowledge-post.hbs ---- - -Sometimes, you might want to let users read or write files on your server. For example, maybe you want to write a forum software without using an actual database. The problem is that you do not want your users to be able to modify or to read arbitrary files on your server, and there sometimes are ways to get around restrictions that should prevent it. Read on to see how you can secure your code against evil attackers trying to mess with your files. - -Poison Null Bytes -================= -Poison null bytes are a way to trick your code into seeing another filename than the one that will actually be opened. This can in many cases be used to circumvent directory traversal protections, to trick servers into delivering files with wrong file types and to circumvent restrictions on the file names that may be used. [A more detailed description is here.](http://groups.google.com/group/nodejs/browse_thread/thread/51f66075e249d767/85f647474b564fde) Always use code like this when accessing files with user-supplied names: - - if (filename.indexOf('\0') !== -1) { - return respond('That was evil.'); - } - -Whitelisting -============ -You won't always be able to use whitelisting, but if you are, do it - it's very easy to implement and hard to get wrong. For example, if you know that all filenames are lowercase alphanumeric strings: - - if (!/^[a-z0-9]+$/.test(filename)) { - return respond('illegal character'); - } - -However, note that whitelisting alone isn't sufficient anymore as soon as you allow dots and slashes - people could enter things like `../../etc/passwd` in order to get files from outside the allowed folder. - -Preventing Directory Traversal -============================== -Directory traversal means that an attacker tries to access files outside of the folder you want to allow him to access. You can prevent this by using nodes built-in "path" module. **Do not implement the stuff in the path module again yourself** - for example, when someone runs your code on a windows server, not handling backslashes like slashes will allow attackers to do directory traversal. - -This example assumes that you already checked the `userSuppliedFilename` variable as described in the "Poison Null Bytes" section above. - - var rootDirectory = '/var/www/'; - -Make sure that you have a slash at the end of the allowed folders name - you don't want people to be able to access `/var/www-secret/`, do you?. - - var path = require('path'); - var filename = path.join(rootDirectory, userSuppliedFilename); - -Now `filename` contains an absolute path and doesn't contain `..` sequences anymore - `path.join` takes care of that. However, it might be something like `/etc/passwd` now, so you have to check whether it starts with the `rootDirectory`: - - if (filename.indexOf(rootDirectory) !== 0) { - return respond('trying to sneak out of the web root?'); - } - -Now the `filename` variable should contain the name of a file or directory that's inside the allowed directory (unless it doesn't exist). diff --git a/locale/uk/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md b/locale/uk/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md deleted file mode 100644 index 436b2423f6ba8..0000000000000 --- a/locale/uk/knowledge/getting-started/control-flow/how-to-write-asynchronous-code.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: How to write asynchronous code -date: '2011-08-26T10:08:50.000Z' -tags: - - asynchronous - - callbacks - - event-emitters -difficulty: 1 -layout: knowledge-post.hbs ---- - -Nodejs promotes an asynchronous coding style from the ground up, in contrast to many of the most popular web frameworks. There are a number of important things to be aware of when learning to write asynchronous code - otherwise, you will often find your code executing in extremely unexpected ways. Take this (general) rule to heart: - -### Use the asynchronous functions, avoid the synchronous ones! - -Many of the functions in Node.js core have both synchronous and asynchronous versions. Under most circumstances, it will be far better for you to use the asynchronous functions - otherwise, why are you using Node.js? - -As a quick example comparing and contrasting the two, using `fs.readFile`: - - var fs = require('fs'); - - fs.readFile('example.file', 'utf8', function (err, data) { - if (err) { - return console.log(err); - } - console.log(data); - }); - - //==================== - - var data = fs.readFileSync('example.file','utf8'); - console.log(data); - -Just looking at these two blocks of code, the synchronous version appears to be more concise. However, the asynchronous version is more complicated for a very good reason. In the synchronous version, the world is paused until the file is finished reading - your process will just sit there, waiting for the OS (which handles all file system tasks). - -The asynchronous version, on the other hand, does not stop time - instead, the callback function gets called when the file is finished reading. This leaves your process free to execute other code in the meantime. - -When only reading a file or two, or saving something quickly, the difference between synchronous and asynchronous file I/O can be quite small. On the other hand, though, when you have multiple requests coming in per second that require file or database IO, trying to do that IO synchronously would be quite thoroughly disastrous for performance. - -### Callbacks -Callbacks are a basic idiom in node.js for asynchronous operations. When most people talk about callbacks, they mean the function that is passed as the last parameter to an asynchronous function. The callback is then later called with any return value or error message that the function produced. For more details, see the article on [callbacks](/uk/knowledge/getting-started/control-flow/what-are-callbacks) - -### Event Emitters -Event Emitters are another basic idiom in node.js. A constructor is provided in Node.js core: `require('events').EventEmitter`. An Event Emitter is typically used when there will be multiple parts to the response (since usually you only want to call a callback once). For more details, see the article on [EventEmitters](/uk/knowledge/getting-started/control-flow/what-are-event-emitters) - -### A gotcha with asynchronous code -A common mistake in asynchronous code with javascript is to write code that does something like this: - - for (var i = 0; i < 5; i++) { - setTimeout(function () { - console.log(i); - }, i); - } - -The unexpected output is then: - - 5 - 5 - 5 - 5 - 5 - -The reason this happens is because each timeout is created and then `i` is incremented. Then when the callback is called, it looks for the value of `i` and it is 5. The solution is to create a closure so that the current value of `i` is stored. For example: - - for (var i = 0; i < 5; i++) { - (function(i) { - setTimeout(function () { - console.log(i); - }, i); - })(i); - } - -This gives the proper output: - - 0 - 1 - 2 - 3 - 4 diff --git a/locale/uk/knowledge/getting-started/control-flow/what-are-callbacks.md b/locale/uk/knowledge/getting-started/control-flow/what-are-callbacks.md deleted file mode 100644 index 0ae067bf09f7f..0000000000000 --- a/locale/uk/knowledge/getting-started/control-flow/what-are-callbacks.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: What are callbacks? -date: '2011-08-26T10:08:50.000Z' -tags: - - javascript - - core - - asynchronous - - callbacks -difficulty: 1 -layout: knowledge-post.hbs ---- - -In a synchronous program, you would write something along the lines of: - - function processData () { - var data = fetchData (); - data += 1; - return data; - } - -This works just fine and is very typical in other development environments. However, if fetchData takes a long time to load the data (maybe it is streaming it off the drive or the internet), then this causes the whole program to 'block' - otherwise known as sitting still and waiting - until it loads the data. Node.js, being an asynchronous platform, doesn't wait around for things like file I/O to finish - Node.js uses callbacks. A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime. - -The node.js way to deal with the above would look a bit more like this: - - function processData (callback) { - fetchData(function (err, data) { - if (err) { - console.log("An error has occurred. Abort everything!"); - return callback(err); - } - data += 1; - callback(data); - }); - } - -At first glance, it may look unnecessarily complicated, but callbacks are the foundation of Node.js. Callbacks give you an interface with which to say, "and when you're done doing that, do all this." This allows you to have as many IO operations as your OS can handle happening at the same time. For example, in a web server with hundreds or thousands of pending requests with multiple blocking queries, performing the blocking queries asynchronously gives you the ability to be able to continue working and not just sit still and wait until the blocking operations come back. This is a major improvement. - -The typical convention with asynchronous functions (which almost all of your functions should be): - - function asyncOperation ( a, b, c, callback ) { - // ... lots of hard work ... - if ( /* an error occurs */ ) { - return callback(new Error("An error has occurred")); - } - // ... more work ... - callback(null, d, e, f); - } - - asyncOperation ( params.., function ( err, returnValues.. ) { - //This code gets run after the async operation gets run - }); - -You will almost always want to follow the [error callback convention](/uk/knowledge/errors/what-are-the-error-conventions), since most Node.js users will expect your project to follow them. The general idea is that the callback is the last parameter. The callback gets called after the function is done with all of its operations. Traditionally, the first parameter of the callback is the `error` value. If the function hits an error, then they typically call the callback with the first parameter being an Error object. If it cleanly exits, then they will call the callback with the first parameter being null and the rest being the return value(s). diff --git a/locale/uk/knowledge/getting-started/control-flow/what-are-event-emitters.md b/locale/uk/knowledge/getting-started/control-flow/what-are-event-emitters.md deleted file mode 100644 index d6491e3789280..0000000000000 --- a/locale/uk/knowledge/getting-started/control-flow/what-are-event-emitters.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: What are Event Emitters? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - asynchronous - - event-emitters -difficulty: 2 -layout: knowledge-post.hbs ---- - -In node.js an event can be described simply as a string with a corresponding callback. An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted. So a simple example ran on the node [REPL](/uk/knowledge/REPL/how-to-use-nodejs-repl): - - var example_emitter = new (require('events').EventEmitter); - example_emitter.on("test", function () { console.log("test"); }); - example_emitter.on("print", function (message) { console.log(message); }); - example_emitter.emit("test"); - example_emitter.emit("print", "message"); - example_emitter.emit("unhandled"); - - > var example_emitter = new (require('events').EventEmitter); - {} - > example_emitter.on("test", function () { console.log("test"); }); - { _events: { test: [Function] } } - > example_emitter.on("print", function (message) { console.log(message); }); - { _events: { test: [Function], print: [Function] } } - > example_emitter.emit("test"); - test //console.log'd - true //return value - > example_emitter.emit("print", "message"); - message //console.log'd - true //return value - > example_emitter.emit("unhandled"); - false //return value - -This demonstrates all the basic functionality of an EventEmitter. The `on` or `addListener` method (basically the subscription method) allows you to choose the event to watch for and the callback to be called. The `emit` method (the publish method), on the other hand, allows you to "emit" an event, which causes all callbacks registered to the event to 'fire', (get called). - -So in the example, we first subscribe to both the `test` and `print` events. Then we emit the `test`, `print`, and `unhandled` events. Since `unhandled` has no callback, it just returns false; the other two run all the attached callbacks and return true. - -In the `print` event, note that we pass an extra parameter - all the extra parameters passed to 'emit' get passed to the callback function as arguments. - -If you use the method `once` instead of `on`, after the callback is fired, it is removed from the list of callbacks. A handy little function if you want to detect only the first time an event has been emitted. - -If you want remove a specific callback, you can use `removeListener`. If you want to remove all callbacks to a specific event, you can use `removeAllListeners`. - - var EventEmitter = require('events').EventEmitter, - ee = new EventEmitter(); - - function callback() { - console.log("Callback has been called!"); - } - - ee.once("event", callback); - ee.emit("event"); - ee.emit("event"); - - ee.on("event", callback); - ee.emit("event"); - ee.emit("event"); - ee.removeListener("event", callback); - ee.emit("event"); - - ee.on("event", callback); - ee.emit("event"); - ee.removeAllListeners("event"); - ee.emit("event"); - - > var ee = new (require('events').EventEmitter); - > var callback = function () { console.log("Callbacked!"); } - > ee.once("event", callback); - { _events: { event: { [Function: g] listener: [Function] } } } - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.emit("event"); - false - - > ee.on("event", callback); - { _events: { event: [Function] } } - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.removeListener("event", callback); - { _events: {} } - > ee.emit("event"); - false - - > ee.on("event", callback); - { _events: { event: [Function] } } - > ee.emit("event"); - Callbacked! //console.log'd - true - > ee.removeAllListeners("event"); - { _events: { event: null } } - > ee.emit("event"); - false - -NOTE: If you want create more than 10 listeners on a single event, you will have to make a call to `ee.setMaxListeners(n)` where n is the max numbers of listeners (with zero being unlimited number of listeners). This is used to make sure you aren't accidentally leaking event listeners. diff --git a/locale/uk/knowledge/getting-started/globals-in-node-js.md b/locale/uk/knowledge/getting-started/globals-in-node-js.md deleted file mode 100644 index 6ba14f3d76163..0000000000000 --- a/locale/uk/knowledge/getting-started/globals-in-node-js.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: The built-in globals in Node.js -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - globals -difficulty: 1 -layout: knowledge-post.hbs ---- - -Node.js has a number of built-in global identifiers that every Node.js developer should have some familiarity with. Some of these are true globals, being visible everywhere; others exist at the module level, but are inherent to every module, thus being pseudo-globals. - -First, let's go through the list of 'true globals': - -- `global` - The global namespace. Setting a property to this namespace makes it globally visible within the running process. -- `process` - Node's built-in `process` module, which provides interaction with the current Node process. [Read More](/uk/knowledge/getting-started/the-process-module) -- `console` - Node's built-in `console` module, which wraps various STDIO functionality in a browser-like way. [Read More](/uk/knowledge/getting-started/the-console-module) -- `setTimeout()`, `clearTimeout()`, `setInterval()`, `clearInterval()` - The built-in timer functions are globals. [Read More](/uk/knowledge/javascript-conventions/what-are-the-built-in-timer-functions) - -As mentioned above, there are also a number of 'pseudo-globals' included at the module level in every module: - -- `module`, `module.exports`, `exports` - These objects all pertain to Node's module system. [Read More](/uk/knowledge/getting-started/what-is-require) -- __filename - The `__filename` keyword contains the path of the currently executing file. Note that this is not defined while running the [Node REPL](/uk/knowledge/REPL/how-to-use-nodejs-repl). -- __dirname - Like `__filename`, the `__dirname` keyword contains the path to the root directory of the currently executing script. Also not present in the Node REPL. -- require() - The `require()` function is a built-in function, exposed per-module, that allows other valid modules to be included. [Read More](/uk/knowledge/getting-started/what-is-require) - -Much of this functionality can be extremely useful for a Node.js developer's daily life - but at the very least, remember these as bad names to use for your own functions! diff --git a/locale/uk/knowledge/getting-started/how-to-debug-nodejs-applications.md b/locale/uk/knowledge/getting-started/how-to-debug-nodejs-applications.md deleted file mode 100644 index 69e0ab0145409..0000000000000 --- a/locale/uk/knowledge/getting-started/how-to-debug-nodejs-applications.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: How to debug a node application -date: '2011-08-26T10:08:50.000Z' -tags: - - debug -difficulty: 1 -layout: knowledge-post.hbs ---- - -Often times, not just in the Node.js community but in software at large, people debug simply with a liberal sprinkle of standard output statements. This allows you to track down where unexpected values are being generated. However, this method can be tedious, or worse yet, not robust enough to detect the real problem. - -### Set up - -Thankfully, through the use of `node-inspector`, we can harness to power of the webkit-debuggers to work with our node.js code. The process itself is simple. - -First, ensure that node-inspector is installed: - - npm install node-inspector -g - -A good example application to experiment with is a basically 'hello world' server with a counter (copied from the `node-inspector` repo): - - var http = require('http'); - - var x = 0; - http.createServer(function (req, res) { - x += 1; - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World ' + x); - }).listen(8124); - console.log('Server running at http://127.0.0.1:8124/'); - -First, we start your node program with debugging enabled. - - node --debug app.js - -which should print something along the lines of `debugger listening on port 5858` to stderr. Take note of the port number, it is the port that the debugger is running on. - -Next, start up `node-inspector`. If your program uses port 8080, then you may have to pass it a custom port. - - node-inspector [--web-port=] - -Finally you fire up a webkit browser such as chrome or safari. and go to `127.0.0.1:8080/debug?port=5858`. Note, if the debugger is listening on a port other than `5858`, you will need to change it. Also, if you passed a custom webport to node-inspector, then you will have to modify the `8080`. - -At this point, you will be met with a fairly empty screen with the `scripts`, `profiles`, and `console` tabs. - -### Scripts tab - -This is just like most webkit/firebug debuggers. It has a list of all the javascript files (including node.js core and third party libraries) which you can select and dive into. To stop the interpreter on a specific line, you set a breakpoint by clicking on the number of the desired line. When the execution is frozen, by a breakpoint or by manually pausing interpretation by pressing the pause button, you can check the callstack and examine all the local, closure, and global variables. You can also modify the code to try and fix behavior. Note that when you modify the code through the script tab, it does not get saved to the file, so you will need to transfer the modifications back by hand. - -### Profiles tab - -To use the profile tab, you need a library called `v8-profiler`: - - npm install v8-profiler - -Next, you have to require it inside the file you are debugging: - - var profiler = require('v8-profiler'); - -Now you can finally enable the `profiles` tab, unfortunately, all you can do from this screen is a heap snapshot. So from the code, you need to select where you want to start to cpu profiler and can select more precise location for heap snapshots. - -To take a heap snapshot, just insert this line in the desired location and optionally pass it a name. - - var snapshot = profiler.takeSnapshot(name); - -To take a cpu profile, just surround the code that you are profiling with the two lines shown below. Optionally, a name can be included to indentify the cpu profile. - - profiler.startProfiling(name); - //..lots and lots of methods and code called..// - var cpuProfile = profiler.stopProfiling([name]); - -As an example how to use these, here is the code given earlier modified to take a cpu profile on every request and take a heap snapshot: after the server is created. - - var http = require('http'); - var profiler = require('v8-profiler'); - - var x = 0; - http.createServer(function (req, res) { - x += 1; - profiler.startProfiling('request '+x); - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.end('Hello World ' + x); - profiler.stopProfiling('request '+x); - }).listen(8124); - profiler.takeSnapshot('Post-Server Snapshot'); - console.log('Server running at http://127.0.0.1:8124/'); - -Note that despite these apis returning objects, it is much easier to sort through the data through the node-inspector interface. Hopefully with these tools, you can make more informed decisions about memory leaks and bottlenecks. - -### Console tab - -Finally, the console tab allows you to use node's REPL in your program's global scope. This has a few gotchas since that means you can not access in local variables. Thus the variables you can read or write are variables that were defined without a `var` statement. The other gotcha is when you use `console.log` refers to node's `console.log` and not webkit's console.log. This means the output goes to stdout and not to your console tab. Otherwise it is a very straightforward node REPL. diff --git a/locale/uk/knowledge/getting-started/how-to-use-util-inspect.md b/locale/uk/knowledge/getting-started/how-to-use-util-inspect.md deleted file mode 100644 index 3be524f13edfe..0000000000000 --- a/locale/uk/knowledge/getting-started/how-to-use-util-inspect.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: How to use util.inspect -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - debug -difficulty: 1 -layout: knowledge-post.hbs ---- - -Node provides a utility function, for debugging purposes, that returns a string representation of an object. `util.inspect()` can be a true lifesaver while working with properties of large, complex objects. - -Let's provide a basic example. `util.inspect()` can be used on any object - a good demonstration will be one of Node's built-in objects. Try this in the REPL (type `node` at your command line with no arguments): - - var util = require('util'); - util.inspect(console); - -The output will be: - - '{ log: [Function], info: [Function], warn: [Function], error: [Function], dir: [Function], time: [Function], timeEnd: [Function], trace: [Function], assert: [Function] }' - -This is a listing of all the enumerable properties of the `console` object. It is also worth noting that `console.dir` is a wrapper around `util.inspect` that uses its default arguments. - -In the REPL, `util.inspect` will immediately return its output - this is not usually the case. In the context of normal Node.js code in a file, something must be done with the output. The simplest thing to do: - - console.log(util.inspect(myObj)); - -`util.inspect` can also be passed several optional arguments, shown here with their defaults: - - util.inspect(object, showHidden=false, depth=2, colorize=true); - -For example, `util.inspect(myObj, true, 7, true)` would inspect `myObj`, showing all the hidden and non-hidden properties up to a depth of `7` and colorize the output. Let's go over the arguments individually. - -The `depth` argument is the number of levels deep into a nested object to recurse - it defaults to 2. Setting it to `null` will cause it to recurse 'all the way', showing every level. Compare the (size of) the outputs of these two `util.inspect` statements in the REPL: - - var http = require('http'); - util.inspect(http, true, 1); - util.inspect(http, true, 3); - -The optional argument `showHidden` is a boolean that determines whether or not the 'non-enumerable' properties of an object will be displayed - it defaults to `false`, which tends to result in vastly more readable output. This isn't something a beginner needs to worry about most of the time, but it's worth demonstrating briefly. Once more, try the following in the REPL: - - var util = require('util'); - util.inspect(console, true); - -Finally, the optional argument `colorize` is a boolean that adds ANSI escape codes to the string output. When logged to a terminal window, it should be pretty printed with colors. - - var util = require('util'); - console.log(util.inspect({a:1, b:"b"}, false,2,true)); diff --git a/locale/uk/knowledge/getting-started/npm/how-to-access-module-package-info.md b/locale/uk/knowledge/getting-started/npm/how-to-access-module-package-info.md deleted file mode 100644 index 1f7457256ae52..0000000000000 --- a/locale/uk/knowledge/getting-started/npm/how-to-access-module-package-info.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: How to access module package info -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - npm -difficulty: 1 -layout: knowledge-post.hbs ---- - -There are many situations in the world of software development where using the wrong version of a dependency or submodule can cause all sorts of pain and anguish - luckily for you, node.js has a module available called pkginfo that can help keep these sorts of troubles at bay. - -Let's take a look at pkginfo - first, install via npm: - - npm install pkginfo - -Now all we need to do is require it, and invoke it. - - var pkginfo = require('pkginfo')(module); - - console.dir(module.exports); - -That would show us the entire contents of the package.json, neatly displayed to our console. If we only wanted certain pieces of information, we just specify them like so: - - var pkginfo = require('pkginfo')(module, 'version', 'author'); - - console.dir(module.exports); - -And only the fields we specify will be shown to us. - -For more information, see http://github.com/indexzero/ . diff --git a/locale/uk/knowledge/getting-started/npm/what-is-npm.md b/locale/uk/knowledge/getting-started/npm/what-is-npm.md deleted file mode 100644 index 05985b7c39e51..0000000000000 --- a/locale/uk/knowledge/getting-started/npm/what-is-npm.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: What is npm? -date: '2011-08-26T10:08:50.000Z' -tags: - - npm -difficulty: 1 -layout: knowledge-post.hbs ---- - -`npm`, short for Node Package Manager, is two things: first and foremost, it is an online repository for the publishing of open-source Node.js projects; second, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management. A plethora of node.js libraries and applications are published on npm, and many more are added every day. These applications can be searched for on http://search.npmjs.org/. Once you have a package you want to install, it can be installed with a single command-line command. - -Let's say you're hard at work one day, developing the Next Great Application. You come across a problem, and you decide that it's time to use that cool library you keep hearing about - let's use Caolan McMahon's [async](http://github.com/caolan/async) as an example. Thankfully, `npm` is very simple to use: you only have to run `npm install async`, and the specified module will be installed in the current directory under `./node_modules/`. Once installed to your `node_modules` folder, you'll be able to use `require()` on them just like they were built-ins. - -Let's look at an example of a global install - let's say `coffee-script`. The npm command is simple: `npm install coffee-script -g`. This will typically install the program and put a symlink to it in `/usr/local/bin/`. This will then allow you to run the program from the console just like any other CLI tool. In this case, running `coffee` will now allow you to use the coffee-script REPL. - -Another important use for npm is dependency management. When you have a node project with a [package.json](/uk/knowledge/getting-started/npm/what-is-the-file-package-json) file, you can run `npm install` from the project root and npm will install all the dependencies listed in the package.json. This makes installing a Node project from a git repo much easier! For example, `vows`, one of Node's testing frameworks, can be installed from git, and its single dependency, `eyes`, can be automatically handled: - -Example: - - git clone https://github.com/cloudhead/vows.git - cd vows - npm install - -After running those commands, you will see a `node_modules` folder containing all of the project dependencies specified in the package.json. diff --git a/locale/uk/knowledge/getting-started/npm/what-is-the-file-package-json.md b/locale/uk/knowledge/getting-started/npm/what-is-the-file-package-json.md deleted file mode 100644 index 7991b412a247b..0000000000000 --- a/locale/uk/knowledge/getting-started/npm/what-is-the-file-package-json.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: What is the file `package.json`? -date: '2011-08-26T10:08:50.000Z' -tags: - - npm - - conventions - - core -difficulty: 2 -layout: knowledge-post.hbs ---- - -All npm packages contain a file, usually in the project root, called `package.json` - this file holds various metadata relevant to the project. This file is used to give information to `npm` that allows it to identify the project as well as handle the project's dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both `npm` and to the end users of the package. The `package.json` file is normally located at the root directory of a Node.js project. - -Node itself is only aware of two fields in the `package.json`: - - { - "name" : "barebones", - "version" : "0.0.0", - } - -The `name` field should explain itself: this is the name of your project. The `version` field is used by npm to make sure the right version of the package is being installed. Generally, it takes the form of `major.minor.patch` where `major`, `minor`, and `patch` are integers which increase after each new release. For more details, look at this spec: http://semver.org . - -For a more complete package.json, we can check out `underscore`: - - { - "name" : "underscore", - "description" : "JavaScript's functional programming helper library.", - "homepage" : "http://documentcloud.github.com/underscore/", - "keywords" : ["util", "functional", "server", "client", "browser"], - "author" : "Jeremy Ashkenas ", - "contributors" : [], - "dependencies" : [], - "repository" : {"type": "git", "url": "git://github.com/documentcloud/underscore.git"}, - "main" : "underscore.js", - "version" : "1.1.6" - } - -As you can see, there are fields for the `description` and `keywords` of your projects. This allows people who find your project understand what it is in just a few words. The `author`, `contributors`, `homepage` and `repository` fields can all be used to credit the people who contributed to the project, show how to contact the author/maintainer, and give links for additional references. - -The file listed in the `main` field is the main entry point for the library; when someone runs `require()`, require resolves this call to `require()`. - -Finally, the `dependencies` field is used to list all the dependencies of your project that are available on `npm`. When someone installs your project through `npm`, all the dependencies listed will be installed as well. Additionally, if someone runs `npm install` in the root directory of your project, it will install all the dependencies to `./node_modules`. - -It is also possible to add a `devDependencies` field to your `package.json` - these are dependencies not required for normal operation, but required/recommended if you want to patch or modify the project. If you built your unit tests using a testing framework, for example, it would be appropriate to put the testing framework you used in your `devDependencies` field. To install a project's `devDependencies`, simply pass the `--dev` option when you use `npm install`. - -For even more options, you can look through the [online docs](https://github.com/npm/npm/blob/master/doc/files/package.json.md) or run `npm help json` diff --git a/locale/uk/knowledge/getting-started/the-console-module.md b/locale/uk/knowledge/getting-started/the-console-module.md deleted file mode 100644 index 5fc41c5241331..0000000000000 --- a/locale/uk/knowledge/getting-started/the-console-module.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: The built-in console module -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - cli - - globals -difficulty: 1 -layout: knowledge-post.hbs ---- - -Anyone familiar with browser-side development has probably used `console.log` for debugging purposes - Node.js has implemented a built-in `console` object to mimic much of this experience. Since we're working server-side, however, it wraps `stdout`, `stdin`, and `stderr` instead of the browser's debugging console. - -Because of this browser parallel, the `console` module has become home to quite a bit of Node's standard output functionality. The simplest is `console.log()`. - - console.log('Hi, everybody!'); - console.log('This script is:', __filename); - console.log(__filename, process.title, process.argv); - -The first, simplest example just prints the provided string to `stdout`. It can also be used to output the contents of variables, as evidenced in #2; furthermore, `console.dir()` is called on any objects passed in as arguments, enumerating their properties. - -NODE.JS PRO TIP: -`console.log()` accepts three format characters, `%s`, `%d`, and `%j`. These format characters can be used to insert string, integer, or JSON data into your output - the order of format characters must match the order of arguments. - - var name = 'Harry', - number = 17, - myObj = { - propOne: 'stuff', - propTwo: 'more stuff' - }; - console.log('My name is %s, my number is %d, my object is %j', name, number, myObj); - -A gotcha with `console.log`, and all functions that depend on it, is that it buffers the output. So if your process ends suddenly, whether it be from an exception or from `process.exit()`, it is entirely possible that the buffered output will never reach the screen. This can cause a great deal of frustration, so watch out for this unfortunate situation. - -`console.error()` works the same as `console.log`, except that the output is sent to `stderr` instead of `stdout`. This is actually an extremely important difference, as `stderr` is always written to synchronously. Any use of `console.error`, or any of the other functions in Node.js core that write to `stderr`, will block your process until the output has all been written. This is useful for error messages - you get them exactly when they occur - but if used everywhere, can greatly slow down your process. - -`console.dir()`, as mentioned above, is an alias for `util.inspect()` - it is used to enumerate object properties. [Read More](/uk/knowledge/getting-started/how-to-use-util-inspect) - -That covers the basic `console` module functionality, but there are a few other methods worth mentioning as well. First, the `console` module allows for the marking of time via `console.time()` and `console.timeEnd()`. Here is an example: - - console.time('myTimer'); - var string = ''; - for (var i = 0; i < 300; i++) { - (function (i) { - string += 'aaaa' + i.toString(); - })(i); - } - console.timeEnd('myTimer'); - -This would determine the amount of time taken to perform the actions in between the `console.time` and `console.timeEnd` calls. - -One last function worth mentioning is `console.trace()`, which prints a stack trace to its location in your code without throwing an error. This can occasionally be useful if you'd like to figure out where a particular failing function was called from. diff --git a/locale/uk/knowledge/getting-started/the-process-module.md b/locale/uk/knowledge/getting-started/the-process-module.md deleted file mode 100644 index 74acb4880dbf8..0000000000000 --- a/locale/uk/knowledge/getting-started/the-process-module.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: How to use the global process module -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - globals -difficulty: 2 -layout: knowledge-post.hbs ---- - -Each Node.js process has a set of built-in functionality, accessible through the global `process` module. The `process` module doesn't need to be required - it is somewhat literally a wrapper around the currently executing process, and many of the methods it exposes are actually wrappers around calls into some of Node's core C libraries. - -## Events - -There are two built-in events worth noting in the `process` module, `exit` and `uncaughtException`. - -The `exit` event fires whenever the process is about to exit. - - process.on('exit', function () { - fs.writeFileSync('/tmp/myfile', 'This MUST be saved on exit.'); - }); - -Code like the above can occasionally be useful for saving some kind of final report before you exit. Note the use of a synchronous file system call - this is to make sure the I/O finishes before the process actually exits. - -The other built-in event is called `uncaughtException`. It fires, as you might guess, whenever an exception has occurred that hasn't been caught or dealt with somewhere else in your program. It's not the ideal way to handle errors, but it can be very useful as a last line of defense if a program needs to stay running indefinitely. - - process.on('uncaughtException', function (err) { - console.error('An uncaught error occurred!'); - console.error(err.stack); - }); - -The default behavior on `uncaughtException` is to print a stack trace and exit - using the above, your program will display the message provided and the stack trace, but will **not** exit. - -## Streams - -The `process` object also provides wrappings for the three `STDIO` streams, `stdin`, `stdout`, and `stderr`. Put briefly, `stdin` is a readable stream (where one would read input from the user), `stdout` is a non-blocking writeable stream (writes to `stdout` are asynchronous, in other words), and `stderr` is a blocking (synchronous) writeable stream. - -The simplest one to describe is `process.stdout`. Technically, most output in Node is accomplished by using `process.stdout.write()` - though most people would never know it. The following is from `console.js` in Node core: - - exports.log = function() { - process.stdout.write(format.apply(this, arguments) + '\n'); - }; - -Since most people are used to the `console.log` syntax from browser development, it was provided as a convenient wrapper. - -Next we have `process.stderr`, which is very similar to `process.stdout` with one key exception - it blocks. When you write to `stderr`, your process blocks until the write is completed. Node.js provides a number of alias functions for output, most of which either end up using `stdout` or `stderr` under the hood. Here's a quick reference list: - -STDOUT, or non-blocking functions: `console.log`, `console.info`, `util.puts`, `util.print` - -STDERR, or blocking functions: `console.warn`, `console.error`, `util.debug` - -Lastly, `process.stdin` is a readable stream for getting user input. See [more on cli input](/uk/knowledge/command-line/how-to-prompt-for-command-line-input). - -## Other Properties - -The `process` object additionally contains a variety of properties that allow you to access information about the running process. Let's run through a few quick examples with the help of the REPL: - - > process.pid - 3290 - > process.version - 'v0.4.9' - > process.platform - 'linux' - > process.title - 'node' - -The `pid` is the OS Process ID, `platform` is something general like 'linux' or 'darwin', and `version` refers to your Node version. `process.title` is a little bit different - while set to `node` by default, it can be set to anything you want, and will be what gets displayed in lists of running processes. - -The `process` module also exposes `process.argv`, an array containing the command-line arguments to the current process, and `process.argc`, an integer representing the number of arguments passed in. Read more on [how to parse command line arguments](/uk/knowledge/command-line/how-to-parse-command-line-arguments) - -`process.execPath` will return the absolute path of the executable that started this process. - -`process.env` contains your environment variables. Try `process.env.HOME`, for example. - -## Methods - -There are also a variety of methods attached to the `process` object, many of which deal with quite advanced aspects of a program. We'll take a look at a few of the more commonly useful ones, while leaving the more advanced parts for another article. - -`process.exit` exits the process. If you call an asynchronous function and then call `process.exit()` immediately afterwards, you will be in a race condition - the asynchronous call may or may not complete before the process is exited. `process.exit` accepts one optional argument - an integer exit code. `0`, by convention, is an exit with no errors. - -`process.cwd` returns the 'current working directory' of the process - this is often the directory from which the command to start the process was issued. - -`process.chdir` is used to change the current working directory. For example: - - > process.cwd() - '/home/avian/dev' - > process.chdir('/home/avian') - > process.cwd() - '/home/avian' - -Finally, on a more advanced note, we have `process.nextTick`. This method accepts one argument - a callback - and places it at the top of the next iteration of the event loop. Some people do something like this: - - setTimeout(function () { - // code here - }, 0) - -This, however, is not ideal. In Node.js, this should be used instead: - - process.nextTick(function () { - console.log('Next trip around the event loop, wheeee!') - }); - -It is much more efficient, and much more accurate. diff --git a/locale/uk/knowledge/getting-started/what-is-node-core-verus-userland.md b/locale/uk/knowledge/getting-started/what-is-node-core-verus-userland.md deleted file mode 100644 index 597e6c8bdda76..0000000000000 --- a/locale/uk/knowledge/getting-started/what-is-node-core-verus-userland.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: What is node core versus userland -date: '2011-08-26T10:08:50.000Z' -tags: - - npm - - core - - userland - - terminology -difficulty: 1 -layout: knowledge-post.hbs ---- - -Occasionally, in the discussions in the NodeJS mailing lists and IRC channels, you may hear things referred to as "node-core" and "userland". - -Of course, traditionally, "userland" or "userspace" refer to everything outside the operating system kernel. In that sense, Node itself is a "userland" program. - -However, in the context of NodeJS, "core" refers to the modules and bindings that are compiled into NodeJS. In general, they provide a hook into very well-understood low-level functionality which almost all networking programs are going to require: TCP, HTTP, DNS, the File System, child processes, and a few other things. If something is fancy enough to argue about, there's a good chance it won't be part of node-core. HTTP is about as big as it gets, and if it wasn't so popular, it'd certainly not be a part of node. - -There are also some things in node-core that are simply too painful to do without in a JavaScript environment, or which have been created to implement some BOM constructs which are not part of the JavaScript language, but may as well be (eg, setTimeout, setInterval, and console). - -Everything else is "userland". This includes: npm, express, request, coffee-script, mysql clients, redis clients, and so on. You can often install these programs using [npm](http://npmjs.org/). - -The question of what is properly "node-core" and what belongs in "userland" is a constant battleground. In general, node is based on the philosophy that it should *not* come with "batteries included". It is easier to move things out of node-core than it is to move them in, which means that core modules must continually "pay rent" in terms of providing necessary functionality that nearly everyone finds valuable. - -## This is a Good Thing. - -One goal of node's minimal core library is to encourage people to implement things in creative ways, without forcing their ideas onto everyone. With a tiny core and a vibrant user space, we can all flourish and experiment without the onerous burden of having to always agree all the time. - -## Userland isn't Less - -If anything, it's more. Building functionality in userland rather than in node-core means: - -* You have a lot more freedom to iterate on the idea. -* Everyone who wants your module can install it easily enough (if you publish it with npm). -* You have freedom to break node conventions if that makes sense for your use-case. - -If you believe that something *really* just *needs* to be part of node's core library set, you should *still* build it as a module! It's much more likely to be pulled into node-core if people have a chance to see your great ideas in action, and if its core principles are iterated and polished and tested with real-world use. - -Changing functionality that is included in node-core is very costly. We do it sometimes, but it's not easy, and carries a high risk of regressions. Better to experiment outside, and then pull it into node-core once it's stable. Once it's usable as a userland package, you may even find that it's less essential to node-core than you first thought. diff --git a/locale/uk/knowledge/getting-started/what-is-require.md b/locale/uk/knowledge/getting-started/what-is-require.md deleted file mode 100644 index f79b5a472f175..0000000000000 --- a/locale/uk/knowledge/getting-started/what-is-require.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: What is require? -date: '2011-08-26T10:08:50.000Z' -tags: - - npm - - core - - globals - - builtin -difficulty: 1 -layout: knowledge-post.hbs ---- - - Node.js follows the CommonJS module system, and the builtin `require` function is the easiest way to include modules that exist in separate files. The basic functionality of `require` is that it reads a javascript file, executes the file, and then proceeds to return the `exports` object. An example module: - - console.log("evaluating example.js"); - - var invisible = function () { - console.log("invisible"); - } - - exports.message = "hi"; - - exports.say = function () { - console.log(exports.message); - } - -So if you run `var example = require('./example.js')`, then `example.js` will get evaluated and then `example` be an object equal to: - - { - message: "hi", - say: [Function] - } - -If you want to set the exports object to a function or a new object, you have to use the `module.exports` object. So for an example: - - module.exports = function () { - console.log("hello world") - } - - require('./example2.js')() //require itself and run the exports object - -It is worth noting that each time you subsequently require an already-required file, the `exports` object is cached and reused. To illustrate this point: - - node> require('./example.js') - evaluating example.js - { message: 'hi', say: [Function] } - node> require('./example.js') - { message: 'hi', say: [Function] } - node> require('./example.js').message = "hey" //set the message to "hey" - 'hey' - node> require('./example.js') //One might think that this "reloads" the file... - { message: 'hey', say: [Function] } //...but the message is still "hey" because of the module cache. - -As you can see from the above, `example.js` is evaluated the first time, but all subsequent calls to `require()` only invoke the module cache, rather than reading the file again. As seen above, this can occasionally produce side effects. - -The rules of where `require` finds the files can be a little complex, but a simple rule of thumb is that if the file doesn't start with "./" or "/", then it is either considered a core module (and the local Node path is checked), or a dependency in the local `node_modules` folder. If the file starts with "./" it is considered a relative file to the file that called `require`. If the file starts with "/", it is considered an absolute path. NOTE: you can omit ".js" and `require` will automatically append it if needed. For more detailed information, see [the official docs](https://nodejs.org/docs/v0.4.2/api/modules.htmll#all_Together...) - -An extra note: if the filename passed to `require` is actually a directory, it will first look for `package.json` in the directory and load the file referenced in the `main` property. Otherwise, it will look for an `index.js`. diff --git a/locale/uk/knowledge/intermediate/how-to-log.md b/locale/uk/knowledge/intermediate/how-to-log.md deleted file mode 100644 index 2da48d382b7ba..0000000000000 --- a/locale/uk/knowledge/intermediate/how-to-log.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: How to log in node.js -date: '2011-08-26T10:08:50.000Z' -tags: - - logging -difficulty: 2 -layout: knowledge-post.hbs ---- - -Many processes, including most servers, write logs in one form or another. Reasons for logging include debugging, keeping track of users and resource usage, and reporting application state. - -### Simple Logging - -The simplest form of logging involves simply using `console.log` or one of the other standard output methods. In this approach, any information is printed to `stdout` where it can either be read by the developer as it occurs, or, for example, redirected to a log file. - - console.log('Web Server started, waiting for connections...'); - -Because it's so simple, console.log is by far the most common way of logging data in node.js. - -### Custom Logging - -Logging only with functions such as `console.log` is not ideal for every use case, however. Many applications have some sort of 'debugging mode', for example, that shows the user much more output than normal execution. To do something like this, a better idea is to write your own simple logger, and use it instead of `console.log`. - -Here is an example of a basic custom logging module with configurable debugging levels. - - var logger = exports; - logger.debugLevel = 'warn'; - logger.log = function(level, message) { - var levels = ['info', 'warn', 'error']; - if (levels.indexOf(level) <= levels.indexOf(logger.debugLevel) ) { - if (typeof message !== 'string') { - message = JSON.stringify(message); - }; - console.log(level+': '+message); - } - } - -Usage would then look like the following: - - var logger = require('./logger'); - logger.debugLevel = 'warn'; - logger.log('info', 'Everything started properly.'); - logger.log('warn', 'Running out of memory...'); - logger.log('error', { error: 'flagrant'}); - -Because `logger.debugLevel` was set to `warn`, the warning message and the error would both be displayed, but the `info` message would not be. - -The advantage here is that the behavior of our logging mechanisms can now be modified and controlled from a central part of our code. In this case, logging levels were added, and messages are converted to JSON if they aren't already in string form. There is a lot more that could be done here - saving logs to a file, pushing them to a database, setting custom colors and formatting the output - but by the time you want that much functionality from your custom logging function, it might be time to use an already-existing library. - -### Winston - multi-transport logging made easy - -[Winston](https://github.com/indexzero/winston) is a multi-transport, asynchronous logging library for node.js. It is conceptually similar to our custom logger, but comes with a wide variety of useful features and functionality baked in. In addition, `winston` is battle-hardened by internal use at Nodejitsu! - -Here is an example of setting up a `winston` logger. This example includes most of the transports one could ever possibly want - please note that most use cases will only warrant a few of these. - - var winston = require('winston'); - - require('winston-riak').Riak; - require('winston-mongo').Mongo; - require('winston-couchdb').Couchdb; - - var logger = new (winston.Logger)({ - transports: [ - new winston.transports.Console(), - new winston.transports.File({ filename: 'path/to/all-logs.log' }), - new winston.transports.Couchdb({ 'host': 'localhost', 'db': 'logs' }), - new winston.transports.Riak({ bucket: 'logs' }), - new winston.transports.MongoDB({ db: 'db', level: 'info'}) - ], - exceptionHandlers: [ - new winston.transports.File({ filename: 'path/to/exceptions.log' }) - ] - }); - -Here, we have instantiated a new `winston` logger, and provided a number of logging transports. Winston has built-in support for configurable logging levels, and provides alias methods for each configured logging level. For example, `winston.warn(x)` is an alias for `winston.log('warn', x)`. Thus, the following: - - logger.warn('Hull Breach Detected on Deck 7!'); - -Would output to the screen: - - warn: Hull Breach Detected on Deck 7! - -Because of the file transport we set up, winston also logged the warning to 'somefile.log'. After the `logger.warn` call we just used, the log file, `somefile.log`, would contain the following output: - - $ cat somefile.log - {'level':'warn','message':'Hull Breach Detected on Deck 7!'} - -Note that winston's file logger formats the logs differently for file logging (JSON in this case) than it does for the console transport. - -Winston also supports logging to Riak, CouchDB, MongoDB and [many other transports](https://github.com/winstonjs/winston/blob/master/docs/transports.md). The `logger.warn` call we used before also put the same message into each database, according to the options we gave to each transport. - -For further information, please see the [thorough documentation for Winston.](https://github.com/indexzero/winston). diff --git a/locale/uk/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md b/locale/uk/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md deleted file mode 100644 index 563fe0524a07b..0000000000000 --- a/locale/uk/knowledge/javascript-conventions/how-to-create-default-parameters-for-functions.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: How To Create Default Parameters for Functions -date: '2011-08-26T10:08:50.000Z' -tags: - - javascript - - builtin -difficulty: 1 -layout: knowledge-post.hbs ---- - -Usually a function will take a set number of parameters, and require that all of them be present before it can be executed successfully. However, you will sometimes run into situations where you want to provide a default value for a parameter or take a variable number of parameters. Unfortunately, javascript does not have a builtin way to do that; over time, however, people have developed idioms to compensate. - -The first idiom is giving a default value for the last parameter. This is done by checking if the last parameter is `undefined` and setting it to a default value if it is. Sometimes people use the idiom: `optionalParameter = optionalParameter || defaultValue`. This can have some undesirable behavior when they pass values that are equal to false such as `false`, `0`, and `""`. So a better way to do this is by explicitly checking that the optional parameter is `undefined`. Here is some code showing the two styles and the differing behavior: - - example = function (optionalArg) { - optionalArg = optionalArg || "No parameter was passed"; - console.log(optionalArg); - } - - betterExample = function (optionalArg) { - if (typeof optionalArg === 'undefined') { - optionalArg = "No parameter was passed"; - } - console.log(optionalArg); - } - - console.log("Without parameter:"); - example(); - betterExample(); - - console.log("\nWith paramater:"); - example("parameter was passed"); - betterExample("parameter was passed"); - - console.log("\nEmpty String:"); - example(""); - betterExample(""); - -If 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 example shows you how to do that: - - example = function (param1, optParam, callback) { - if (typeof callback === 'undefined') { - // only two parameters were passed, so the callback is actually in `optParam` - callback = optParam; - - //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); - -More complicated cases require more code and can obscure the meaning of what you are trying to do. It then becomes a good idea to use helper functions - for example, suppose we wanted to take a variable amount of parameters and pass them all to the callback. You could try to accomplish this by manipulating the `arguments` variable - however, it is just easier to use the [vargs](https://github.com/cloudhead/vargs) library. As you can see by this code, it makes the whole process a little simpler: - - var Args = require("vargs").Constructor; - - example = function () { - var args = new Args(arguments); - args.callback.apply({},args.all); - } - - example("The first parameter", console.log); - example("The first parameter", "and second parameter", console.log); - example("The first parameter", "and second parameter", "and third parameter", console.log); - example("The first parameter", "and second parameter", "and third parameter", "etc", console.log); diff --git a/locale/uk/knowledge/javascript-conventions/using-ECMA5-in-nodejs.md b/locale/uk/knowledge/javascript-conventions/using-ECMA5-in-nodejs.md deleted file mode 100644 index fa616cf020de8..0000000000000 --- a/locale/uk/knowledge/javascript-conventions/using-ECMA5-in-nodejs.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Using ECMA5 in node.js -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - builtin - - globals -difficulty: 2 -layout: knowledge-post.hbs ---- - -When developing in the browser there are many wonderful built in JavaScript functions that we can't use because certain browsers don't implement them. As a result, most developers never use them. In Node, however we can assume that everyone has the same JavaScript implementation and as such can use these wonderful functions and not implement them over and over in our own libraries. - -The following is a list of some interesting api bits that aren't considered safe to use in a web setting but are built in to node's V8 engine. - -Note that V8 implements all of ECMA 3rd edition and parts of the new stuff in the [ECMA 5th edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - -## Syntax extensions - -* `var obj = { get a() { return "something" }, set a() { "do nothing" } }` getter/setter syntax - -## Array - -* `Array.isArray(array)` - Returns true if the passed argument is an array. - -## Array.prototype - -* `indexOf(value)` - Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. -* `lastIndexOf(value)` - Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. -* `filter(callback)` - Creates a new array with all of the elements of this array for which the provided filtering function returns true. -* `forEach(callback)` - Calls a function for each element in the array. -* `every(callback)` - Returns true if every element in this array satisfies the provided testing function. -* `map(callback)` - Creates a new array with the results of calling a provided function on every element in this array. -* `some(callback)` - Returns true if at least one element in this array satisfies the provided testing function. -* `reduce(callback[, initialValue])` - Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. -* `reduceRight(callback[, initialValue])` - Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. - -## Date - -* `Date.now()` - Returns the numeric value corresponding to the current time. - -## Date.prototype - -* `toISOString()` - - -## Object - -* `Object.create(proto, props)` - Creates a new object whose prototype is the passed in parent object and whose properties are those specified by props. -* `Object.keys(obj)` - Returns a list of the ownProperties of an object that are enumerable. -* `Object.defineProperty(obj, prop, desc)` - Defines a property on an object with the given descriptor -* `Object.defineProperties(obj, props)` - Adds own properties and/or updates the attributes of existing own properties of an object -* `Object.getOwnPropertyNames(obj)` - Returns a list of the ownProperties of an object including ones that are not enumerable. -* `Object.getPrototypeOf(obj)` - Returns the prototype of an object. -* `Object.getOwnPropertyDescriptor(obj, property)` - Returns an object with keys describing the description of a property (value, writable, enumerable, configurable) -* `Object.preventExtensions(obj)` - Prevents any new properties from being added to the given object. -* `Object.isExtensible(obj)` - Checks if Object.preventExtensions() has been called on this object. -* `Object.seal(obj)` - Prevents code from adding or deleting properties, or changing the descriptors of any property on an object. Property values can be changed however. -* `Object.isSealed(obj)` - Checks if Object.seal() has been called on this object. -* `Object.freeze(obj)` - Same as Object.seal, except property values cannot be changed. -* `Object.isFrozen(obj)` - Checks if Object.freeze() has been called on this object. - -## Object.prototype - -* `__defineGetter__(name, callback)` - (Mozilla extension, not ECMAScript 5) Associates a function with a property that, when accessed, executes that function and returns its return value. -* `__defineSetter__(name, callback)` - (Mozilla extension, not ECMAScript 5) Associates a function with a property that, when set, executes that function which modifies the property. -* `__lookupGetter__(name)` - (Mozilla extension, not ECMAScript 5) Returns the function associated with the specified property by the __defineGetter__ method. -* `__lookupSetter__(name)` - (Mozilla extension, not ECMAScript 5) Returns the function associated with the specified property by the __defineSetter__ method. -* `isPrototypeOf(obj)` - (EcmaScript 3 and 5) Returns true if `this` is a prototype of the passed in object. - -## Function.prototype - -* `bind(thisArg[, arg1[, argN]])` - Sets the value of 'this' inside the function to always be the value of thisArg when the function is called. Optionally, function arguments can be specified (arg1, arg2, etc) that will automatically be prepended to the argument list whenever this function is called. - -## JSON - -* `JSON.stringify(obj [, replacer [, space]])` - Takes any serializable object and returns the JSON representation as a string [More info](https://developer.mozilla.org/En/Using_JSON_in_Firefox) -* `JSON.parse(string)` - Takes a well formed JSON string and returns the corresponding JavaScript object. - -## String.prototype - -* `trim()` - Trims whitespace from both ends of the string -* `trimRight()` - Trims whitespace from the right side of the string -* `trimLeft()` - Trims whitespace from the left side of the string - -## Property Descriptor Defaults - -* `value` - undefined -* `get` - undefined -* `set` - undefined -* `writable` - false -* `enumerable` - false -* `configurable` - false - -# Missing features - -* `Object.__noSuchMethod__` (Mozilla extension, not ECMAScript 5) -* `"use strict";` syntax extension ([v8 issue](http://code.google.com/p/v8/issues/detail?id=919)) diff --git a/locale/uk/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md b/locale/uk/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md deleted file mode 100644 index e7c9d2f1e5631..0000000000000 --- a/locale/uk/knowledge/javascript-conventions/what-are-the-built-in-timer-functions.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: What are the built-in timer functions? -date: '2011-08-26T10:08:50.000Z' -tags: - - core - - builtin - - globals -difficulty: 1 -layout: knowledge-post.hbs ---- - -There are two built-in timer functions, `setTimeout` and `setInterval`, which can be used to call a function at a later time. For an example usage: - - 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: - - setTimeout: It's been one second! - setInterval: It's been one second! - setInterval: It's been one second! - setInterval: It's been one second! - setInterval: It's been one second! - ... - -As you can see the parameters to both are the same. The number second parameter says how long in milliseconds to wait before calling the function passed into the first parameter. The difference between the two functions is that `setTimeout` calls the callback only once while `setInterval` will call it over and over again. - -Typically you want to be careful with `setInterval` because it can cause some undesirable effects. If, for example, you wanted to make sure your server was up by pinging it every second, you might think to try something like this: - - setInterval(ping, 1000); - -This can cause problems, however, if your server is slow and it takes, say, 3 seconds to respond to the first request. In the time it takes to get back the response, you would have sent off 3 more requests - not exactly desirable! This isn't the end of the world when serving small static files, but if you doing an expensive operation such as database query or any complicated computation this can have some undesirable results. A common solution looks like this: - - var recursive = function () { - console.log("It has been one second!"); - setTimeout(recursive,1000); - } - recursive(); - -As you can see, it makes a call to the `recursive` function which, as it completes, makes a call to `setTimeout(recursive, 1000)` which makes it call `recursive` again in 1 second - thus having near the same effect as setInterval while being resilient to the unintended errors that can pile up. - -You can clear the timers you set with `clearTimeout` and `clearInterval`. Their usages are very simple: - - function never_call () { - console.log("You should never call this function"); - } - - var id1 = setTimeout(never_call,1000); - var id2 = setInterval(never_call,1000); - - clearTimeout(id1); - clearInterval(id2); - -So if you keep track of the return values of the timers, you can easily unhook the timers. - -The final trick for the timer objects is you can pass parameters to the callback by passing more parameters to setTimeout and setInterval: - - setTimeout(console.log, 1000, "This", "has", 4, "parameters"); - setInterval(console.log, 1000, "This only has one"); - - This has 4 parameters - This only has one - This only has one - This only has one - This only has one - This only has one - ... diff --git a/locale/uk/knowledge/javascript-conventions/what-are-truthy-and-falsy-values.md b/locale/uk/knowledge/javascript-conventions/what-are-truthy-and-falsy-values.md deleted file mode 100644 index 82c0ff96ba163..0000000000000 --- a/locale/uk/knowledge/javascript-conventions/what-are-truthy-and-falsy-values.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -date: '2011-08-26T10:08:50.000Z' -tags: - - truthy - - falsy - - types - - coercion -title: 'What are "truthy" and "falsy" values?' -difficulty: 4 -layout: knowledge-post.hbs ---- - -JavaScript is weakly typed language. That means different types can be -used in operations and the language will try to convert the types -until the operation makes sense. - - console.log("1" > 0); // true, "1" converted to number - console.log(1 + "1"); // 11, 1 converted to string - -Type conversion also applys when values are used in unary boolean -operations, most notably if statements. If a value converts to the -boolean true, then it is said to be "truthy". If it converts to false -it is "falsy". - - var myval = "value"; - if(myval) { - console.log("This value is truthy"); - } - - myval = 0; - if(!myval) { - console.log("This value is falsy"); - } - -Since most values in javascript are truthy, e.g. objects, arrays, most -numbers and strings, it's easier to identify all of the falsy -values. These are: - - false // obviously - 0 // The only falsy number - "" // the empty string - null - undefined - NaN - -Note that all objects and arrays are truthy, even empty ones. - -Truthiness and Falsiness also come into play with logical -operators. When using logical AND/OR, the values will be converted -based on truthiness or falsyness and then the expression will resolve -to the last truthy value. Short circuit rules apply. Here's an -extended example. - - var first = "truthy" - , second = "also truthy"; - - var myvalue = first && second; - console.log(myvalue); // "also truthy" - - first = null; - second = "truthy"; - - myvalue = first || second; - console.log(myvalue); // "truthy" - - myvalue2 = second || first; - console.log(myvalue2); // "truthy" - - var truthy = "truthy" - , falsy = 0; - - myvalue = truthy ? true : false; - myvalue = falsy ? true : false; diff --git a/locale/uk/knowledge/javascript-conventions/what-is-json.md b/locale/uk/knowledge/javascript-conventions/what-is-json.md deleted file mode 100644 index 67274f6081f98..0000000000000 --- a/locale/uk/knowledge/javascript-conventions/what-is-json.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -date: '2011-08-26T10:08:50.000Z' -tags: - - json - - stringify - - parse -title: What is JSON? -difficulty: 5 -layout: knowledge-post.hbs ---- - -JavaScript Object Notation, or JSON, is a lightweight data format that -has become the defacto standard for the web. JSON can be represented -as either a list of values, e.g. an Array, or a hash of properties and -values, e.g. an Object. - - // a JSON array - ["one", "two", "three"] - - // a JSON object - { "one": 1, "two": 2, "three": 3 } - -## Encoding and Decoding - -JavaScript provides 2 methods for encoding data structures to json and -encoding json back to javascript objects and arrays. They are both -available on the `JSON` object that is available in the global scope. - -`JSON.stringify` takes a javascript object or array and returns a -serialized string in the JSON format. - - var data = { - name: "John Doe" - , age: 32 - , title: "Vice President of JavaScript" - } - - var jsonStr = JSON.stringify(data); - - console.log(jsonStr); - - // prints '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}' - -`JSON.parse` takes a JSON string and decodes it to a javascript data -structure. - - var jsonStr = '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'; - - var data = JSON.parse(jsonStr); - - console.log(data.title); - - // prints 'Vice President of JavaScript' - -## What is valid JSON? - -There are a few rules to remember when dealing with data in JSON -format. There are several gotchas that can produce invalid JSON as well. - -* Empty objects and arrays are okay -* Strings can contain any unicode character, this includes object properties -* `null` is a valid JSON value on it's own -* All object properties should always be double quoted -* Object property values must be one of the following: String, Number, Boolean, Object, Array, null -* Number values must be in decimal format, no octal or hex representations -* Trailing commas on arrays are not allowed - -These are all examples of valid JSON. - - {"name":"John Doe","age":32,"title":"Vice President of JavaScript"} - - ["one", "two", "three"] - - // nesting valid values is okay - {"names": ["John Doe", "Jane Doe"] } - - [ { "name": "John Doe"}, {"name": "Jane Doe"} ] - - {} // empty hash - - [] // empty list - - null - - { "key": "\uFDD0" } // unicode escape codes - -These are all examples of bad JSON formatting. - - { name: "John Doe", 'age': 32 } // name and age should be in double quotes - - [32, 64, 128, 0xFFF] // hex numbers are not allowed - - { "name": "John Doe", age: undefined } // undefined is an invalid value - - // functions and dates are not allowed - { "name": "John Doe" - , "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT') - , "getName": function() { - return this.name; - } - } - -Calling `JSON.parse` with an invalid JSON string will result in a -SyntaxError being thrown. If you are not sure of the validity of your -JSON data, you can anticipate errors by wrapping the call in a -try/catch block. - -Notice that the only complex values allowed in JSON are objects and -arrays. Functions, dates and other types are excluded. This may not -seem to make sense at first. But remember that JSON is a data format, -not a format for transferring complex javascript objects along with -their functionality. - -## JSON in other languages - -Although JSON was inspired by the simplicity of javascript data -structures, it's use is not limited to the javascript language. Many -other languages have methods of transferring native hashes and lists -into stringified JSON objects. Here's a quick example in ruby. - - require 'json' - - data = { :one => 1 } - puts data.to_json - - # prints "{ \"one\": 1 }" diff --git a/locale/uk/knowledge/javascript-conventions/what-is-the-arguments-object.md b/locale/uk/knowledge/javascript-conventions/what-is-the-arguments-object.md deleted file mode 100644 index dd0f347e062a2..0000000000000 --- a/locale/uk/knowledge/javascript-conventions/what-is-the-arguments-object.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -date: '2011-08-26T10:08:50.000Z' -tags: - - truthy - - falsy - - types - - coercion -title: What is the arguments object? -difficulty: 4 -layout: knowledge-post.hbs ---- - -The `arguments` object is a special construct available inside all -function calls. It represents the list of arguments that were passed -in when invoking the function. Since javascript allows functions to be -called with any number args, we need a way to dynamically discover and -access them. - -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 standard -property of `arguments` is callee. This always refers to the function -currently being executed. Here's an example that illustrates the -properties of `arguments`. - - var myfunc = function(one) { - arguments.callee === myfunc; - arguments[0] === one; - arguments[1] === 2; - arguments.length === 3; - } - - 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. Since a normal for loop -works, this is pretty easy. - - var args = []; - for(var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - -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. - - myfunc.apply(obj, arguments). - - // concat arguments onto the - Array.prototype.concat.apply([1,2,3], arguments). - - // turn arguments into a true array - var args = Array.prototype.slice.call(arguments); - - // cut out first argument - args = Array.prototype.slice.call(arguments, 1);