| |
|
开发:
C++知识库
Java知识库
JavaScript
Python
PHP知识库
人工智能
区块链
大数据
移动开发
嵌入式
开发工具
数据结构与算法
开发测试
游戏开发
网络协议
系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程 数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁 |
-> JavaScript知识库 -> Official_Node.js -- introduction -> 正文阅读 |
|
[JavaScript知识库]Official_Node.js -- introduction |
Introduction to Node.jsNode.js is an open-source and cross-platform Node.js runs the A Node.js app runs in 1?? Node.js provides generally, libraries in Node.js are written using When Node.js performs an This allows Node.js to handle thousands of 4?? Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language. In Node.js the new ECMAScript standards can be used without problems, as you don’t have to wait for all your users to update their browsers - you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags. An Example Node.js ApplicationThe most common example Hello World of Node.js is a web server:
This code first includes the Node.js Node.js has a fantastic standard library, including first-class support for networking. The The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running. Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object). Those 2 objects are essential to handle the HTTP call. The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data. The second is used to return data to the caller. In this case with:
we set the statusCode property to 200, to indicate a successful response. We set the Content-Type header:
and we close the response, adding the content as an argument to
A brief history of Node.jsJavaScript is a programming language that was created at Netscape as a scripting tool to manipulate web pages inside their browser, Netscape Navigator. Part of the business model of Netscape was to sell Web Servers, which included an environment called Netscape LiveWire that could 👯 create dynamic pages using server-side JavaScript. Unfortunately, Netscape LiveWire wasn’t very successful and server-side JavaScript wasn’t popularized until recently, by the introduction of Node.js. One key factor that led to the rise of Node.js was the JavaScript engines also became considerably better as many browsers competed to offer users the best performance. Development teams behind major browsers worked hard to offer better support for JavaScript and find ways to ?? make JavaScript run faster. The engine that Node.js uses under the hood, V8 (also known as Chrome V8 for being the open-source JavaScript engine of The Chromium Project), improved significantly due to this competition. Node.js happened to be built in the right place and right time, but luck isn’t the only reason why it is popular today. It introduces a lot of innovative thinking and approaches for JavaScript server-side development that have already helped many developers. 2009
2010 2011
2012
2013 2014
2015
2016
2017
2018
2019
2020
2021
Differences between Node.js and the BrowserBoth the browser and Node.js use JavaScript as their programming language. Building apps that run in the browser is a completely different thing than building a Node.js application. Despite the fact that it’s always JavaScript, there are some key differences that make the experience radically different. From the perspective of a frontend developer who extensively uses JavaScript, Node.js apps bring with them a huge advantage 1?? the comfort of programming everything - the frontend and the backend - in a single language. You have a huge opportunity because we know how hard it is to fully, deeply learn a programming language, and by using the same language to perform all your work on the web - both on the client and on the server, you’re in a unique position of advantage. What changes is the ecosystem. In the browser, most of the time what you are doing is interacting with the DOM, or other Web Platform APIs like Cookies. Those do not exist in Node.js, of course. You don’t have the And in the browser, we don’t have all the 2??nice APIs that Node.js provides through its modules, like the filesystem access functionality. Another big difference is that in Node.js you 3?? control the environment. Unless you are building an open source application that anyone can deploy anywhere, you know which version of Node.js you will run the application on. Compared to the browser environment, where you don’t get the luxury to choose what browser your visitors will use, this is very convenient. This means that you can write all the modern ES6-7-8-9 JavaScript that your Node.js version supports. Since JavaScript moves so fast, but browsers can be a bit slow to upgrade, sometimes on the web you are stuck with using older JavaScript / ECMAScript releases. You can use Babel to transform your code to be ES5-compatible before shipping it to the browser, but in Node.js, you won’t need that. Another difference is that Node.js 4?? uses the CommonJS module system, while in the browser we are starting to see the ES Modules standard being implemented. In practice, this means that for the time being you use The V8 JavaScript EngineV8 is the name of the JavaScript engine that powers Google Chrome. It’s the thing that takes our JavaScript and executes it while browsing with Chrome. V8 provides the runtime environment in which JavaScript executes. The DOM, and the other Web Platform APIs are provided by the browser. The cool thing is that the The Node.js ecosystem is huge and thanks to V8 which also powers desktop apps, with projects like Electron. The quest for performanceV8 is written in In this V8 introduction, we will ignore the implementation details of V8: they can be found on more authoritative sites (e.g. the V8 official site), and they change over time, often radically. V8 is always evolving, just like the other JavaScript engines around, to speed up the Web and the Node.js ecosystem. On the web, there is a race for performance that’s been going on for years, and we (as users and developers) benefit a lot from this competition because we 👊 get faster and more optimized machines year after year. CompilationJavaScript is generally considered an interpreted language, but modern JavaScript engines no longer just interpret JavaScript, they compile it. This has been happening since 2009, when the SpiderMonkey JavaScript compiler was added to Firefox 3.5, and everyone followed this idea. JavaScript is internally compiled by V8 with 🕛 just-in-time (JIT) compilation to speed up the execution. This might seem counter-intuitive, but since the introduction of Google Maps in 2004, JavaScript has evolved from a language that was generally executing a few dozens of lines of code to complete applications with thousands to hundreds of thousands of lines running in the browser. Our applications now can run for hours inside a browser, rather than being just a few form validation rules or simple scripts. In this new world, compiling JavaScript makes perfect sense because while it might take a little bit more to have the JavaScript ready, once done it’s going to be much more performant than purely interpreted code. How to exit from a Node.js programThe When Node.js runs this line, the process is immediately forced to terminate. This means that any callback that’s pending, any network request still being sent, any filesystem access, or processes writing to If this is fine for you, you can pass an integer that signals the operating system the exit code:
By default the exit code is You can read more on exit codes at https://nodejs.org/api/process.html#process_exit_codes You can also set the
and when the program ends, Node.js will return that exit code. A program will gracefully exit when all the processing is done. Many times with Node.js we start servers, like this HTTP server:
This program is never going to end. If you call In this case you need to send the command
You can send this signal from inside the program, in another function:
Or from another Node.js running program, or any other app running in your system that knows the PID of the process you want to terminate. How to read environment variables from Node.jsThe The below code runs
That will pass the user
Here is an example that accesses the
In the same way you can access any custom environment variable you set. If you have multiple environment variables in your node project, you can also create an
In your js file
How to use the Node.js REPLuse node in REPL mode:
Start simple and enter
Use the tab to autocompleteThe cool thing about the REPL is that it’s interactive. As you write your code, if you press the Exploring JavaScript objectsTry entering the name of a JavaScript class, like The REPL will print all the properties and methods you can access on that class Explore global objectsYou can inspect the globals you have access to by typing The _ special variableIf after some code you type Dot commandsThe REPL has some special commands, all starting with a dot
The REPL knows when you are typing a multi-line statement without the need to invoke For example if you start typing an iteration like this:
and you press
If you type Node.js, accept arguments from the command lineYou can pass any number of arguments when invoking a Node.js application using
Arguments can be standalone or have a key and a value. For example:
or
This changes how you will retrieve this value in the Node.js code. The way you retrieve it is using the It exposes an The first element is the full path of the The second element is the full path of the file being executed. All the additional arguments are present from the third position going forward. You can iterate over all the arguments (including the node path and the file path) using a loop:
You can get only the additional arguments by creating a new array that excludes the first 2 params:
If you have one argument without an index name, like this:
you can access it using
In this case:
This time you need to use double dashes before each argument name:
Output to the command line using Node.jsNode.js provides a It is basically the same as the The most basic and most used method is If you pass an object, it will render it as a string. You can pass multiple variables to
and Node.js will print both. We can also format pretty phrases by passing variables and a format specifier. For example:
Example:
Clear the console
Counting elements
count the number of times a string is printed, and print the count next to it
The console.countReset() method resets counter used with console.count().
Print the stack traceThere might be cases where it’s useful to print the call stack trace of a function, maybe to answer the question how did you reach that part of the code? You can do so using
Calculate the time spentYou can easily calculate how much time a function takes to run, using
stdout and stderrAs we saw console.log is great for printing messages in the Console. This is what’s called the standard output, or
It will not appear in the console, but it will appear in the error log. Color the outputYou can color the output of your text in the console by using escape sequences. An escape sequence is a set of characters that identifies a color. Example:
You can try that in the Node.js REPL, and it will print However, this is the low-level way to do this. The simplest way to go about coloring the console output is by using a library. Chalk is such a library, and in addition to coloring it also helps with other styling facilities, like making text bold, italic or underlined. You install it with
Using Check the project link posted above for more usage examples. Create a progress barProgress is an awesome package to create a progress bar in the console. Install it using This snippet creates a 10-step progress bar, and every 100ms one step is completed. When the bar completes we clear the interval:
Accept input from the command line in Node.jsHow to make a Node.js CLI program interactive? Node.js since version 7 provides the readline module to perform exactly this: get input from a readable stream such as the
This piece of code asks the username, and once the text is entered and the user presses enter, we send a greeting. The In this callback function, we close the readline interface.
If you need to require a password, it’s best not to echo it back, but instead show a The simplest way is to use the readline-sync package which is very similar in terms of the API and handles this out of the box. A more complete and abstract solution is provided by the Inquirer.js package. You can install it using
Inquirer.js lets you do many things like asking multiple choices, having radio buttons, confirmations, and more. It’s worth knowing all the alternatives, especially the built-in ones provided by Node.js, but if you plan to take CLI input to the next level, Inquirer.js is an optimal choice. Expose functionality from a Node.js file using exportsNode.js has a built-in module system. A Node.js file can import functionality exposed by other Node.js files. When you want to import something you use
to import the functionality exposed in the In this file, functionality must be exposed before it can be imported by other files. Any other object or variable defined in the file by default is private and not exposed to the outer world. This is what the When you assign an You can do so in 2 ways. The first is to assign an object to
The second way is to add the exported object as a property of
or directly
And in the other file, you’ll use it by referencing a property of your import:
or
What’s the difference between The first exposes 👪 ?
module.exports
An introduction to the npm package managerIntroduction to npm
In January 2017 over 350000 packages were reported being listed in the npm registry, making it the biggest single language code repository on Earth, and you can be sure there is a package for (almost!) everything. It started as a way to download and manage dependencies of Node.js packages, but it has since become a tool used also in frontend JavaScript. There are many things that
Downloads
Installing all dependenciesIf a project has a
it will install everything the project needs, in the Installing a single packageYou can also install a specific package by running
Furthermore, since npm 5, this command adds Often you’ll see more flags added to this command:
The difference between devDependencies and dependencies is that the former contains development tools, like a testing library, while the latter is bundled with the app in production. Updating packagesUpdating is also made easy, by running
You can specify a single package to update as well:
VersioningIn addition to plain downloads, Many times you’ll find that a library is only compatible with a major release of another library. Or a bug in the latest release of a lib, still unfixed, is causing an issue. Specifying an explicit version of a library also helps to keep everyone on the same exact version of a package, so that the whole team runs the same version until the In all those cases, versioning helps a lot, and Running TasksThe package.json file supports a format for specifying command line tasks that can be run by using
For example:
It’s very common to use this feature to run Webpack:
So instead of typing those long commands, which are easy to forget or mistype, you can run
Where does npm install the packages?When you install a package using
By default, when you type an
the package is installed in the current file tree, under the As this happens, A global installation is performed using the
When this happens, npm won’t install the package under the local folder, but instead, it will use a global location. Where, exactly? The On macOS or Linux this location could be If you use I for example use The package.json guideIf you work with JavaScript, or you’ve ever interacted with a JavaScript project, Node.js or a frontend project, you surely met the What’s that for? What should you know about it, and what are some of the cool things you can do with it? The The file structureHere’s an example package.json file:
It’s empty! There are no fixed requirements of what should be in a If you’re building a This is another package.json:
It defines a
All those properties are used by either Properties breakdownThis section describes the properties you can use in detail. We refer to “package” but the same thing applies to Most of those properties are only used on https://www.npmjs.com/, others by scripts that interact with your code, like nameSets the package name. Example:
The name must be less than 214 characters, must not have spaces, it can only contain lowercase letters, hyphens ( This is because when a package is published on If you published this package publicly on GitHub, a good value for this property is the GitHub repository name. versionIndicates the current version of the package. Example:
This property follows the semantic versioning (semver) notation for versions, which means the version is always expressed with 3 numbers: The first number is the major version, the second the minor version and the third is the patch version. There is a meaning in these numbers: a release that only 1?? fixes bugs is a mainSets the entry point for the package. When you import this package in an application, that’s where the application will ?? search for the module exports. Example:
The package-lock.json fileThe goal of Find the installed version of an npm packageTo see the version of all installed npm packages, including their dependencies:
To get only your top-level packages (basically, the ones you told npm to install and you listed in the Install an older version of an npm package
global
listing all the previous versions of a package. You can do it with
Update all the Node.js dependencies to their latest versionIf there is a
Use To 👀 discover new releases of the packages, you run Semantic Versioning using npmWhen you make a new release, you don’t just up a number as you please, but you have rules:
Uninstalling npm packages
Using the
npm global or local packagesThe main difference between local and global packages is this:
In your code you can only require local packages:
so when should you install in one way or another? In general, all packages should be installed locally. This makes sure you can have dozens of applications in your computer, all running a different version of each package if needed. Updating a global package would make all your projects use the new release, and as you can imagine this might cause nightmares in terms of maintenance, as some packages might break compatibility with further dependencies, and so on. All projects have their own local version of a package, even if this might appear like a waste of resources, it’s minimal compared to the possible negative consequences. A package should be installed globally when it provides an executable command that you run from the shell (CLI), and it’s reused across projects. You can also install executable commands locally and run them using npx, but some packages are just better installed globally. You probably have some packages installed globally already on your system. You can see them by running
on your command line. npm dependencies and devDependenciesWhen you install an npm package using The package is automatically listed in the package.json file, under the When you add the
When you go in production, if you type You need to set the npx
will do the job. Other scenarios include:
and many more. |
|
JavaScript知识库 最新文章 |
ES6的相关知识点 |
react 函数式组件 & react其他一些总结 |
Vue基础超详细 |
前端JS也可以连点成线(Vue中运用 AntVG6) |
Vue事件处理的基本使用 |
Vue后台项目的记录 (一) |
前后端分离vue跨域,devServer配置proxy代理 |
TypeScript |
初识vuex |
vue项目安装包指令收集 |
|
上一篇文章 下一篇文章 查看所有文章 |
|
开发:
C++知识库
Java知识库
JavaScript
Python
PHP知识库
人工智能
区块链
大数据
移动开发
嵌入式
开发工具
数据结构与算法
开发测试
游戏开发
网络协议
系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程 数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁 |
360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年5日历 | -2025/5/1 2:01:34- |
|
网站联系: qq:121756557 email:121756557@qq.com IT数码 |