How to use nodejs
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!');
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;
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
(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;
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
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('写入文件成功!');
}
});
(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');
(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
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');
});
(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);
});
(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']);
(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;
});
});
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!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
How to use del and ins tags in HTML
Aug 12, 2025 am 11:38 AM
Thetagisusedtomarkdeletedtext,optionallywithdatetimeandciteattributestospecifywhenandwhythedeletionoccurred.2.Thetagindicatesinsertedcontent,alsosupportingdatetimeandciteforcontextabouttheaddition.3.Thesetagscanbecombinedtoshowdocumentrevisionsclearl
How to use CSS gradients for backgrounds
Aug 17, 2025 am 08:39 AM
CSSgradientsprovidesmoothcolortransitionswithoutimages.1.Lineargradientstransitioncolorsalongastraightlineusingdirectionsliketobottomorangleslike45deg,andsupportmultiplecolorstopsforcomplexeffects.2.Radialgradientsradiatefromacentralpointusingcircleo
How to use CSS selectors effectively
Aug 11, 2025 am 11:12 AM
When using CSS selectors, low-specific selectors should be used first to avoid excessive limitations; 1. Understand the specificity level and use them reasonably in the order of type, class, and ID; 2. Use multi-purpose class names to improve reusability and maintainability; 3. Use attributes and pseudo-class selectors to avoid performance problems; 4. Keep the selector short and clear scope; 5. Use BEM and other naming specifications to improve structural clarity; 6. Avoid the abuse of tag selectors and:nth-child, and give priority to the use of tool classes or modular CSS to ensure that the style is controllable for a long time.
How can you make an HTML element editable by the user?
Aug 11, 2025 pm 05:23 PM
Yes, you can make HTML elements editable by using the contenteditable attribute. The specific method is to add contenteditable="true" to the target element. For example, you can edit this text, and the user can directly click and modify the content. This attribute is suitable for block-level and in-line elements such as div, p, span, h1 to h6. The default value is "true" to be editable, "false" to be non-editable, and "inherit" to inherit the parent element settings. In order to improve accessibility, it is recommended to add tabindex="0&quo
How to create a responsive testimonial slider with CSS
Aug 12, 2025 am 09:42 AM
It is feasible to create a responsive automatic carousel slider with pure CSS, just combine HTML structure, Flexbox layout, and CSS animation. 2. First build a semantic HTML container containing multiple recommendation terms, each .item contains reference content and author information. 3. Use the parent container to set display:flex, width:300% (three slides) and apply overflow:hidden to achieve horizontal arrangement. 4. Use @keyframes to define a translateX transformation from 0% to -100%, and combine animation: scroll15slinearinfinite to achieve seamless automatic scrolling. 5. Add media
How to use the address tag in HTML
Aug 15, 2025 am 06:24 AM
Thetagisusedtodefinecontactinformationfortheauthororownerofadocumentorsection;1.Useitforemail,physicaladdress,phonenumber,orwebsiteURLwithinanarticleorbody;2.Placeitinsideforauthorcontactorinfordocument-widecontact;3.StyleitwithCSSasneeded,notingdefa
How to create a select dropdown in HTML
Aug 16, 2025 am 05:32 AM
Use and create drop-down menus; 2. Add tags and names with the and name attributes; 3. Set default options with selected attributes; 4. Group options; 5. Add required attributes to achieve required verification; a complete HTML drop-down menu should contain tags, names, options grouping and verification to ensure complete and user-friendly functions.
How to create subscript and superscript in HTML
Aug 20, 2025 am 11:37 AM
TocreatesubscriptandsuperscripttextinHTML,usetheandtags.1.Usetoformatsubscripttext,suchasinchemicalformulaslikeH₂O.2.Usetoformatsuperscripttext,suchasinexponentslike10²orordinalslike1ˢᵗ.3.Combinebothtagswhenneeded,asinscientificnotationlike²³⁵₉₂U.The


