1. The first nodejs application
n1_hello.js
console.log('hello word!');
Execute the file in the command line cmd (Open the command line at this file):
node n1_hello.js
Return the result from cmd on the command line:
hello word!
2. Basic format of nodejs
//步骤一:引入require模块,require指令载入http模块 var http = require('http'); //步骤二:创建服务器 http.createServer(function (request, response) { // 发送 HTTP 头部 // HTTP 状态值: 200 : OK // 内容类型: text/html response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'}); //步骤三:接受请求与响应请求 if(request.url!=='/favicon.ico'){ ...... // 发送响应数据 response.end('');//必须有,没有则没有协议尾 } }).listen(8000); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8000/');
3. Nodejs calling function
----------------- Call local function--------------------------------
var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'}); if(request.url!=='/favicon.ico'){ fun1(response); // 发送响应数据 response.end(''); } }).listen(8000); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8000/'); function fun1(res){ console.log('fun1'); res.write('hello,我是fun1'); }
-----------------Call external functions-----------------------------
Note: External functions must be written in module.exports, exports is the interface exposed by the module
------------(1) Only call one function- ----------
In the main program:
var http = require('http'); var otherfun = require("./models/otherfuns.js");//调用外部页面的fun2 http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'}); if(request.url!=='/favicon.ico'){ otherfun(response);//支持一个函数时 response.end(''); } }).listen(8000); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8000/');
otherfuns.js
function fun2(res){ console.log('fun2'); res.write('你好!,我是fun2'); } module.exports = fun2;//只支持一个函数
------------(2) Call multiple functions-----------
Main program Medium:
var http = require('http'); var otherfun = require("./models/otherfuns.js");//调用写函数的外部页面otherfuns.js http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'}); if(request.url!=='/favicon.ico'){ //todo 以对象.方法名调用 otherfun.fun2(response); otherfun.fun3(response); //todo 以字符串调用对应函数(结果同上) //otherfun['fun2'](response); //otherfun['fun3'](response); response.end(''); } }).listen(8000); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8000/'); }
otherfuns.js Medium
module.exports={ fun2:function(res){//匿名函数 console.log('fun2'); res.write('你好!,我是fun2');//在页面中输出 }, fun3:function(res){ console.log('fun3'); res.write('你好!,我是fun3'); }, ...... }
4. Preliminary nodejs routing
Main program n4_rout.js:
var http = require('http'); //引入url模块 var url = require('url'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'}); if(request.url!=='/favicon.ico'){ var pathname = url.parse(request.url).pathname; pathname=pathname.replace(/\//,'');//替换掉前面的/ console.log(pathname); response.end(''); } }).listen(8000); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8000/');
Execute the file in the command line cmd, access: http://localhost:8000/, enter the routing address here, as shown below, and observe Command Line.
5. Nodejs reads files
Main program:
var http = require('http'); var optfile=require('./models/optfile');//导入文件 http.createServer(function (request, response) { // 发送 HTTP 头部 // HTTP 状态值: 200 : OK // 内容类型: text/html response.writeHead(200, {'Content-Type': 'text/html;chaset=utf-8;'}); if(request.url!=='/favicon.ico'){//清除第2次访问 optfile.readfileSync('./views/login.html');//同步调用读取文件readfileSync()方法 //optfile.readfile('./views/login.html',response);//异步步调用读取文件readfile()方法 response.end('ok!!!!!');//todo 不写没有协议尾 console.log('主程序执行完毕!'); } }).listen(8000); // 终端打印如下信息 console.log('Server running at http://127.0.0.1:8000/');
optfile In .js:
var fs=require('fs');//Node 导入文件系统模块(fs)语法 导入fs操作文件的类 module.exports={ readfileSync:function(path){ // 同步读取 var data = fs.readFileSync(path,'utf-8');//以中文读取同步文件路径path console.log("同步方法执行完毕。"); }, readfile:function(path){ // 异步读取 fs.readFile(path,function (err, data) { if (err) { console.error(err); }else{ console.log("异步读取: " + data.toString()); } }); console.log("异步方法执行完毕。"); }, }
Result: In command line cmd
(1) When reading the file synchronously:
(2) When reading files asynchronously: (commonly used)
In the web page: all are:
The above is the entire content of this article. I hope that the content of this article can bring some help to everyone's study or work. I also hope to support the PHP Chinese website!
For more articles related to nodejs basic applications, please pay attention to the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

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

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools
