Node.js
Node.js Basics
Concept
Simply put, Node.js is JavaScript running on the server.
Node.js is a platform built on top of Chrome’s JavaScript runtime.
Node.js is an event-driven I/O server-side JavaScript environment. Based on Google’s V8 engine, the V8 engine executes Javascript very fast and has very good performance.
Chrome V8 engine
Browser kernel engines are mainly divided into two categories:
- Rendering engine: It can convert HTML/CSS/JavaScript text and corresponding resource files into image results. The main role of the rendering engine is to convert resource files into user-visible results.
- JavaScript engine: capable of parsing and compiling JavaScript code.
The V8 engine is a JavaScript engine implementation, originally designed by some language experts, and later acquired by Google, and then Google made it open source. V8 is developed using C++. Before running JavaScript, V8 compiles it into native machine code and uses methods such as inline caching (inline caching) compared to other JavaScript engines that convert it into bytecode or interpret execution to improve performance. With these features, JavaScript programs run as fast as binary programs under the V8 engine. V8 supports many operating systems, such as windows, linux, android, and other hardware architectures, such as IA32, X64, ARM, etc., and has good portability and cross-platform features.
Download and install
Download
The installation package can be downloaded from the Node.js official website, and the documentation can be found on the Node.js Chinese website.
Install
Fool-style installation, you don’t need to change anything except the path, all the way to next.
Environment variables are automatically configured.
Test
-
View version number
node -v
-
run a hello world
node hello.js
Set cache and prefix location
npm config set cache "D:\develop\ ode.js\ ode_cache" npm config set prefix "D:\develop\ ode.js\ ode_global"
Modular
Prior to ES6, there was no modular syntax for frontends. Programmers use some plug-ins (for example: require.js and sea.js) to achieve front-end modularization. But since ES6, JS has native support for modularity.
Modular specification:
- AMD
- cmd
- CommonJS
- ECMAScript 2015
Front-end modularity
JS file is set as a module
When introducing a JS file in HTML, add a type="module"
attribute to set the JS file as a modular file:
<script src="./index.js" type="module"> </script>
Load module
To load another module in a module import 'relative_path'
:
import './js/a.js'; import './js/b.js';
Exposure and introduction
-
Expose data via
export
in a JS file:// a.js export var num = 100; export function foo() {<!-- --> console.log('b.js foo'); }
-
In a JS file, only one piece of data is exposed by default, which can be exposed through
export default
:// b.js var num = 100; export default num;
-
The data exposed through
export
is loaded in another JS file throughimport from
to get the data, and you can useas
to change the variable name:import {<!-- --> num as n, foo } from './a.js';
-
The data exposed through
export default
is in another JS file. Whenimport from
, you can name any variable to receive the exposed data:import b from './b.js';
Backend modularity
CommonJS
CommonJS is a server-side specification for Nodejs. CommonJS stipulates that each JS file is an independent module, and each module has its own independent scope. By default, data cannot be accessed between each other.
require()
require()
is used to introduce another JS file in a JS file, and the imported file path can be set.
require('./a.js');
Files imported through require
will be run and loaded.
Path rules
- Between directories at the same level, the path must add
./
. - The suffix
.js
of the imported JS file can be omitted. - There is only one file name in the path. By default, this file loads the module that comes with Nodejs or the module downloaded by a third party.
Module cache
When we load a module for the first time through require()
, Nodejs will cache the module. When the module is loaded later, it will be read directly from the cache.
In other words, if the same file is required multiple times, it will only be executed once.
Exposure and introduction
By default, JS files in Nodejs cannot access data with each other. If data exchange is required, the following two steps are required:
-
Expose data via
module.exports
in a JS file:module.exports.num = 10; module.exports = {<!-- --> num: 10 };
-
Imported via
require()
in another JS file:const aJS = require('./a.js'); const {<!-- --> num } = require('./a.js');
Nodejs built-in module
fs file system
-
introduce
const fs = require('fs');
-
read file asynchronously
fs.readFile('./test.txt', 'utf-8', function (err, data) {<!-- --> if (err) {<!-- --> console.log('Failed to read file content'); } else {<!-- --> console.log('File content read successfully', data); } });
-
Read files synchronously
try {<!-- --> const data = fs.readFileSync('./test.txt', 'utf-8'); console.log('File content read successfully', data); } catch (error) {<!-- --> console.log('Failed to read file content'); }
-
Overwrite
fs.writeFile('./test.txt', 'This is the newly written content', function (err) {<!-- --> console. log('err', err); }); fs.writeFileSync('./test.txt', 'This is the newly written content for synchronization');
-
Append write
fs.appendFile('./test.txt', '\ This is the new content added', (err) => {<!-- --> console. log(err); }) fs.appendFileSync()
-
copy file content
fs.copyFile('./test.txt', './newTest.txt', (err) => {<!-- --> console. log(err); })
-
Delete Files
fs.unlink('./newTest.txt', err => {<!-- --> console. log(err); })
-
rename file
fs.rename('./bbb.txt', './data/bbb.txt', err => {<!-- --> console. log(err); })
-
create folder
fs.mkdir('./data/b', (err) => {<!-- --> console. log(err); }); fs.mkdirSync('./data/a')
-
delete folder
Only empty folders can be deleted
fs.rmdir('./data', err => {<!-- --> console. log(err); })
-
read folder contents
fs. readdir('./data/b', (err, data) => {<!-- --> console. log('err', err); console. log('data', data); })
-
Determine whether a file\folder exists
fs.access('./dat', (err) => {<!-- --> if (err) {<!-- --> console.log('does not exist'); } else {<!-- --> console.log('exists'); } })
-
check status
fs.stat('./data', (err, stats) => {<!-- --> console.log('Is it a file', stats.isFile()); console.log('Is it a folder', stats.isDirectory()); })
path path
- introduce
- unfinished terminal