ref: https://nodejs.dev/an-introduction-to-the-npm-package-manager
基本来自官网,链接如上。为了加深理解和印象稍作整理如下:
1. Node.js
1.1 Difference between Node.js and Browser
- Can use JS to write backend…
- 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 document, window and all the other objects that are provided by the browser.
And in the browser, we don’t have all the nice APIs that Node.js provides through its modules, like the filesystem access functionality.
- Another big difference is that in Node.js you control the environment, 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
- Since JavaScript moves so fast, but browsers can be a bit slow and users a bit slow to upgrade, 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 uses the CommonJS module system, while in the browser we are starting to see the ES Modules standard being implemented.
2. V8 Javascript Engine
2.1 V8 Intro
- V8 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 JavaScript engine is independent of the browser in which it’s hosted.
2.2 Other JS Engines
Other browsers have their own JavaScript engine:
Firefox has SpiderMonkey
Safari has JavaScriptCore (also called Nitro)
Edge has Chakra
3. Node.js Program
node app.js // run
process.exit(1) // or:
process.exitCode = 1
// sometimes need:
process.on('SIGTERM', () => {
// SIGTERM is the signal that tells a process to gracefully terminate
server.close(() => {
console.log('Process terminated')
})
})
// or
process.kill(process.pid, 'SIGTERM')
4. Read environment variables from Node.js
process.env.NODE_ENV // "development" // is set to development by default.
// Setting it to "production" before the script runs will tell Node.js that this is a production environment.
// also can access customer env in the same way