How to use nodejs

王林
Release: 2023-05-08 09:32:07
Original
5298 people have browsed it

Node.js is an open source, cross-platform JavaScript runtime environment based on the Chrome JavaScript runtime. It not only supports server-side JavaScript development, but also supports Web application development, and can even be used to develop IoT devices. Node.js is characterized by an event-driven, non-blocking I/O model, which can easily handle high-concurrency requests. It is one of the preferred development tools for modern WEB applications.

So, how to use Node.js? The following will be divided into the following parts to introduce the installation, basic syntax, common modules and case applications of Node.js.

1. Install Node.js

First, download the corresponding version of the Node.js installation package from the Node.js official website https://nodejs.org and install it.
After the installation is completed, open the command line tool (cmd or powershell under Windows, Terminal under Mac or Linux) and enter the "node -v" command. If the version number of Node.js is output, the installation is successful.

2. Node.js basic syntax

Next, let’s take a look at the basic syntax of Node.js.

(1) console.log() output

console.log() is one of the most commonly used functions in Node.js, used to output console information. The following example:

console.log('Hello, World!');
Copy after login

This code can be run using "node file name.js" in the command line tool, and the output result is: "Hello, World!"

(2) Variable Declaration

Variables in Node.js can be declared using three keywords: var, let, and const. Among them, let and const are new features of ES6.

var num = 1;
let name = 'Tom';
const PI = 3.14;
Copy after login

Variables declared by var can be overwritten, variables declared by let can be reassigned, and variables declared by const are not allowed to be reassigned.

(3) Function definition and call

Use the function keyword to define functions in Node.js, and there is no need to specify the function return type. As an example:

function add(a, b) {
    return a + b;
}
console.log(add(1, 2)); // 输出3
Copy after login

(4) Module import and export

In Node.js, a module is an independent file that contains functions and variables related to a certain function. In a module, we can export the functions or variables that need to be exposed through module.exports, and in other modules we can import and use it through the require() function.

Suppose we now have a math.js file with the following content:

function add(a, b) {
    return a + b;
}
module.exports = add;
Copy after login

We can use the require() function in another file to get the add function exported in the module and call it:

const add = require('./math');
console.log(add(1, 2)); // 输出3
Copy after login

3. Node.js Common Modules

Node.js provides a large number of built-in modules for handling various tasks, such as file system operations, network communications, encryption and decryption, etc. We can call related modules through the require() function.

(1) File system module (fs)

fs module provides file system related operations. These include file reading and writing, directory operations, file stream operations, etc. For example:

const fs = require('fs');
// 读取文件内容
fs.readFile('test.txt', function(err, data) {
    if (err) {
        console.log('读取文件失败:', err);
    } else {
        console.log('读取文件成功:', data.toString());
    }
});
// 写入文件
fs.writeFile('test.txt', 'Hello, Node.js!', function(err) {
    if (err) {
        console.log('写入文件失败:', err);
    } else {
        console.log('写入文件成功!');
    }
});
Copy after login

(2) Network communication module (http)

The http module is used to implement server and client programs related to the HTTP protocol. We can use it to create HTTP servers and clients to handle network communication. As an example:

const http = require('http');
http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
}).listen(8080);
console.log('服务器已经启动,请访问http://localhost:8080');
Copy after login

(3) Encryption and decryption module (crypto)

The crypto module is used to provide encryption and decryption functions. It can be used to generate random numbers, hashing algorithms, symmetric encryption, asymmetric encryption, and more. As an example:

const crypto = require('crypto');
const hash = crypto.createHash('md5');
hash.update('Hello World!');
console.log(hash.digest('hex')); // 输出27d64f37a0f7fca3a63f6ddc39135c01
Copy after login

4. Node.js case application

Finally, let’s take a look at the specific application scenarios of Node.js, including web servers, command line tools, automated tasks and desktops Applications etc.

(1) Web server

Node.js can easily build a Web server and is suitable for handling high concurrent requests, so it is very suitable for Web server development.

For example, we can use Node.js to build a blog website based on the Express framework. The code is as follows:

const express = require('express');
const path = require('path');
const app = express();
// 设置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 处理静态资源
app.use(express.static(path.join(__dirname, 'public')));
// 首页
app.get('/', function (req, res) {
    res.render('index', { title: '首页', message: '欢迎来到我的博客!' });
});
// 关于我
app.get('/about', function (req, res) {
    res.render('about', { title: '关于我', message: '我是一名Web前端开发工程师。' });
});
// 联系我
app.get('/contact', function (req, res) {
    res.render('contact', { title: '联系我', message: '欢迎联系我。' });
});
// 启动服务器
app.listen(3000, function () {
    console.log('服务器已经启动,请访问http://localhost:3000');
});
Copy after login

(2) Command line tools

Node.js can easily develop command line tools, including code generators, data crawlers, server monitoring tools, etc.

For example, we can use Node.js to develop a command-line translation tool. The code is as follows:

const request = require('request');
const qs = require('querystring');
const API_URL = 'http://fanyi.baidu.com/v2transapi';
// 命令行输入参数
const word = process.argv[2];
// 发送翻译请求
request.post(API_URL, {
    form: {
        from: 'en', // 翻译源语言为英语
        to: 'zh', // 翻译目标语言为中文
        query: word,
        simple_means_flag: 3, // 返回详细翻译结果
        sign: ''
    }
}, function(err, res, body) {
    const data = JSON.parse(body);
    console.log(data.trans_result.data[0].dst);
});
Copy after login

(3) Automated tasks

Node.js is very suitable for developing automated tasks, such as build tools, code inspection tools, unit testing tools, etc.

For example, we can use Node.js and Gulp to build an automated build tool for compressing JS and CSS code. The code is as follows:

const gulp = require('gulp');
const uglify = require('gulp-uglify');
const minifyCss = require('gulp-minify-css');
// 压缩JS文件
gulp.task('uglify-js', function () {
    return gulp.src('src/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest('public'));
});
// 压缩CSS文件
gulp.task('minify-css', function () {
    return gulp.src('src/**/*.css')
        .pipe(minifyCss())
        .pipe(gulp.dest('public'));
});
// 默认任务
gulp.task('default', ['uglify-js', 'minify-css']);
Copy after login

(4) Desktop application

Node.js is also suitable for developing desktop applications, especially cross-platform applications. For example, Electron is a cross-platform application based on Node.js and Chromium. Platform desktop application development platform.

For example, we can develop a simple desktop notepad application using Node.js and Electron. The code is as follows:

const electron = require('electron');
const {app, BrowserWindow} = electron; // 控件和事件句柄
let mainWindow; // 主窗口
app.on('ready', function() {
    // 创建主窗口
    mainWindow = new BrowserWindow({ width: 800, height: 600 });
    mainWindow.loadURL(`file://${__dirname}/index.html`);
    // 打开开发者工具
    mainWindow.webContents.openDevTools();
    // 处理窗口关闭事件
    mainWindow.on('closed', function() {
        mainWindow = null;
    });
});
Copy after login

The above is the basic introduction and application scenarios of Node.js. If you want to learn more about Node.js, you can refer to the official Node.js documentation and various Node.js tutorials.

The above is the detailed content of How to use nodejs. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!