JavaScript and node JS brief introduction

JavaScript tutorial

Introduction to JavaScript

JavaScript is a high-level programming language, which is executed by interpretation. It is a dynamic type, object-oriented (prototype based) interpretation language. JavaScript is a language based on prototype and function first. It is a multi paradigm language. It supports object-oriented programming, imperative programming and functional programming. It provides syntax to manipulate text, arrays, dates and regular expressions. It does not support I/O, such as network, storage and graphics, but these can be supported by its host environment.

Write directly to HTML output stream

Document. Can only be used in html output Write is equivalent to adding a string of html code to the original html code. If you use this method after the document is loaded, the entire document will be overwritten

document.write("<h1>This is a title</h1>");
document.write("<p>This is a paragraph.</p>");

Response to events

<button type="button" onclick="alert('welcome!')">Point me!</button>

Change HTML content

x=document.getElementById("demo");  //Find element
x.innerHTML="Hello JavaScript";    //Change content

Change HTML style

x=document.getElementById("demo")  //Find element 
x.style.color="#ff0000 "; / / change style

Verify input

if isNaN(x) {
    alert("Not a number");
}

javascript usage

Scripts in HTML must be between tags.

Scripts can be placed in and sections of HTML pages.

To insert JavaScript into an HTML page, use

Will tell JavaScript where to start and end.
<script>
alert("My first JavaScript");
</script>

JavaScript in

JavaScript writes text to the HTML when the page loads

<!DOCTYPE html>
<html>
<body>
.
.
<script>
document.write("<h1>This is a title</h1>");
document.write("<p>This is a paragraph</p>");
</script>
.
.
</body>
</html>

JavaScript functions and events

JavaScript code is put into a function, which can be called when an event occurs.

function myFunction()
{
    document.getElementById("demo").innerHTML="My first JavaScript function";
}

External JavaScript

External files usually contain code used by multiple web pages.

The file extension of the external JavaScript file is js. Not used

To use external files, please

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

javascript output

javaScript can output data in different ways:

Use window Alert() pops up a warning box.
Use document The write () method writes the content to the HTML document.
Use innerHTML to write to HTML elements.
Use console Log() is written to the browser console.

JavaScript syntax

JavaScript literal

In programming languages, fixed values are generally called literal values, such as 3.14.

The literal quantity of Number can be integer or decimal, or scientific count (e).

3.14

1001

123e5

A String literal can use single or double quotation marks

"John Doe"

'John Doe'

Expression literals are used to calculate

5 + 6

5 * 10

Array literal defines an array

[40, 100, 1, 5, 25, 10]

The Object literal defines an Object

{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

Function literal defines a function:

function myFunction(a, b) { return a * b;}

JavaScript variables

In programming languages, variables are used to store data values.

JavaScript uses the keyword var to define variables and the equal sign to assign values to variables

var x, length

x = 5

length = 6

JavaScript operator

javaScript uses arithmetic operators to evaluate values
avaScript uses assignment operators to assign values to variables

(5 + 6) * 10

x = 5
y = 6
z = (x + y) * 10

JavaScript statement

In HTML, JavaScript statements send commands to browsers.

Statements are separated by semicolons:

x = 5 + 6;
y = x * 10;

JavaScript keyword

JavaScript keywords are used to identify the action to be performed.

Like any other programming language, JavaScript retains some keywords for its own use.

The var keyword tells the browser to create a new variable

JavaScript also retains some keywords, which are not used in the current language version, but will be used in future JavaScript extensions.

The following are the most} important reserved keywords in JavaScript (in alphabetical order):

JavaScript comments

Not all JavaScript statements are "commands". The content after the double slash / / will be ignored by the browser

JavaScript data type

JavaScript has many data types: numbers, strings, arrays, objects, and so on:

var length = 16;                                  // Number is assigned by numeric literal
var points = x * 10;                              // Number is assigned by expression literal
var lastName = "Johnson";                         // String assignment by string literal
var cars = ["Saab", "Volvo", "BMW"];              // Array is assigned by array literal
var person = {firstName:"John", lastName:"Doe"};  // Object is assigned by object literal

Concept of data type

In programming language, data type is a very important content.

In order to manipulate variables, it is important to understand the concept of data types.

JavaScript function

JavaScript statements can be written in functions, which can be referenced repeatedly:

Reference a function = call a function (execute the statement in the function).

function myFunction(a, b) {
    return a * b;                                // Returns the result of multiplying a by b
}

JavaScript letter case

JavaScript is case sensitive.

When writing JavaScript statements, please pay attention to whether to turn off the case toggle key.

The function getelementbyid is different from getelementbyid.

Similarly, the variable myvariable is different from myvariable.

JavaScript character set

JavaScript uses Unicode character sets.

Unicode covers all characters, including punctuation and other characters.

Load in sequence. Execute $(function() after loading{
}); Equal statement

Asynchronous programming

In front-end programming (even in the back-end sometimes), when we deal with some short and fast operations, such as calculating the result of 1 + 1, we can often complete it in the main thread. As a thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event does not end, the interface will not be able to process other requests.

Now there is a button. If we set its onclick event as an endless loop, when this button is pressed, the whole web page will lose response.

In order to avoid this situation, we often use sub threads to complete things that may take long enough to be noticed by users, such as reading a large file or making a network request. Because the child thread is independent of the main thread, even if it is blocked, it will not affect the operation of the main thread. However, the sub thread has one limitation: once it is launched, it will lose synchronization with the main thread, and we can't determine its end. If we need to deal with some things after the end, such as processing information from the server, we can't merge it into the main thread.

In order to solve this problem, asynchronous operation functions in JavaScript often realize the result processing of asynchronous tasks through callback functions.

Callback function

Callback function is a function that tells it when we start an asynchronous task: what to do after you finish the task. In this way, the main thread hardly cares about the state of the asynchronous task, and it will start and end well by itself.

function print() {
    document.getElementById("demo").innerHTML="RUNOOB!";
}
setTimeout(print, 3000);

Asynchronous AJAX

In addition to the setTimeout function, asynchronous callbacks are widely used in AJAX programming.
XMLHttpRequest is often used to request XML or JSON data from a remote server.
The onload and onerror properties of XMLHttpRequest are functions that are called when the request succeeds and when the request fails.

var xhr = new XMLHttpRequest();
 
xhr.onload = function () {
    // Output received text data
    document.getElementById("demo").innerHTML=xhr.responseText;
}
 
xhr.onerror = function () {
    document.getElementById("demo").innerHTML="Request error";
}
 
// Send asynchronous GET request
xhr.open("GET", "https://www.runoob.com/try/ajax/ajax_info.txt", true);
xhr.send();
$.get("https://www.runoob.com/try/ajax/demo_test.php",function(data,status){
    alert("data: " + data + "\n state: " + status);
});

Arrow function

ES6 adds arrow function.

The syntax of arrow function expression is more concise than ordinary function expression.

(parameter 1, parameter 2,..., parameter n) = > {function declaration}

(parameter 1, parameter 2,..., parameter n) = > expression (single)
//Equivalent to: (parameter 1, parameter 2,..., parameter n) > {return expression;}
Parentheses are optional when there is only one parameter:

(single parameter) = > {function declaration}
Single argument = > {function declaration}
Functions without arguments should be written in parentheses:

() = > {function declaration}
example

// ES5
var x = function(x, y) {
     return x * y;
}
 
// ES6
const x = (x, y) => x * y;

Some arrow functions do not have their own this. It is not suitable to define a method of an object.

When we use the arrow function, the arrow function will help us bind the value of the outer layer this by default, so the value of this in the arrow function is the same as that of the outer layer this.

The arrow function cannot be promoted, so it needs to be defined before use.

const is safer than var because the function expression is always a constant.

If the function part is just a statement, you can omit the return keyword and braces {}. This is a good habit:

Node.js tutorial

introduce

Node.js is JavaScript running on the server side.

Node.js is a platform based on Chrome JavaScript runtime.

Node.js is an event driven I/O server JavaScript environment. It is based on Google's V8 engine. The V8 engine executes JavaScript very fast and has very good performance.

Node.js is JavaScript running on the server side. Therefore, being familiar with the use of JavaScript will help you learn node js.

Installation package

npm i -g ***

vscode debugging

Error: vscode can't find node js binary node:path does not exits
Specify runtimeExecutable

where node

Puppeter practice

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false, slowMo: 200 });
  const page = await browser.newPage();
  await page.goto('http://puppeteerjs.com/');
  await page.screenshot({path: 'puppeteerjs.png'});
  content = await page.content()
 
  const metrics = await page.evaluate(() => JSON.stringify(window.performance));

 
  console.info(JSON.parse(metrics));
  await browser.close();
})();

Keywords: Javascript node.js Front-end crawler

Added by samrat_php on Sun, 20 Feb 2022 13:35:25 +0200