search
HomeWeb Front-endFront-end Q&AWhat are the official modules of nodejs?

Nodejs official modules include: 1. path module, used to process file paths; 2. until module; 3. fs module, API of file operating system; 4. events module; 5. http module; 6. jade module; 7. Express module.

What are the official modules of nodejs?

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, Dell G3 computer.

Nodejs built-in modules refer to the beauty provided in addition to the default syntax. No need to download, they can be imported directly. Just write the name.

nodejs built-in module:

1. Path module:

is used to process file paths .

path.normalize(路径解析,得到规范路径);
path.join(路径合并);
path.resolve(获取绝对路径);
path.relative(获取相对路径)。
......

2. Until module:

Make up for the lack of js functions and add new APIs.

util.format(格式化输出字符串);
util.isArray(检查是否为数组);
util.RegExp(是不是正则);
util.isDate(是不是日期型);
util.inherits(child,parent)实现继承;

3. fs module:

API of file operating system

fs.readFile(filename,[options],callback); 读取文件。
fs.writeFile(filename,data,[options],callback);写文件。
fs.appendFile(filename,data,[options],callback);以追加的方式写文件。
fs.open(filename,flags,[mode],callback); 打开文件。
filename:文件名,必须。
data:写入的数据或者buffer流。
flags:操作标识,打开方式,r w。
[options]:指定权限,读、写、执行。是否可续写。
callback:读取文件后的回调函数。function(err,data);
fs.mkdir(path,[mode],callback);创建目录。
fs.readdir(path,callback);读取目录。
fs.exists(path,callback);查看文件与目录是否存在。
fs.utimes(path,atime,mtime,callback);修改文件的访问时间和修改时间。
fs.rename(oldfilename,newfilename,callback);重命名文件名或者目录。
fs.rmdir(path,callback);删除空目录。
path:被创建目录的完整路径以及目录名。
[mode]:目录权限,默认0777(可读可写可执行)。
atime:新的访问时间。
ctime:新的修改时间。
oldfilename、newfilename  旧名字和新名字。
callback:创建完目录后的回调函数。

4. events module

events module only provides one object: events.EventEmitter.

[The core of EventEmitter is the encapsulation of event triggering and event listener functions. 】

Each event of EventEmitter consists of an event name and several parameters. The event name is a string, which usually expresses certain semantics. For each event, EventEmitter supports several event listeners. When an event is triggered, the event listeners registered to this event are called in turn, and the event parameters are passed as callback function parameters.

5. http module

http.createServer(function(){});创建服务器。
http.get('路径',callback);发送get请求。
http.request(options,callback);发送请求。
options:options是一个类似关联数组的对象,表示请求的参数,callback作为回调函数,需要传递一个参数。
options常用的参数有host、port(默认为80)、method(默认为GET)、path(请求的相对于根的路径,默认是“/”。

get:

var http=require("http");
 var options={
    hostname:"cn.bing.com",
    port:80
}
 
var req=http.request(options,function(res){
    res.setEncoding("utf-8");
    res.on("data",function(chunk){
        console.log(chunk.toString())
    });
    console.log(res.statusCode);
});
req.on("error",function(err){
    console.log(err.message);
});
req.end();

post:

var http=require("http");
var querystring=require("querystring");
 
var postData=querystring.stringify({
    "content":"我真的只是测试一下",
    "mid":8837
});
 
var options={
    hostname:"www.imooc.com",
    port:80,
    path:"/course/document",
    method:"POST",
    headers:{
        "Accept":"application/json, text/JavaScript, */*; q=0.01",
        "Accept-Encoding":"gzip, deflate",
        "Accept-Language":"zh-CN,zh;q=0.8",
        "Connection":"keep-alive",
        "Content-Length":postData.length,
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie":"imooc_uuid=6cc9e8d5-424a-4861-9f7d-9cbcfbe4c6ae; imooc_isnew_ct=1460873157; loginstate=1;
         apsid=IzZDJiMGU0OTMyNTE0ZGFhZDAzZDNhZTAyZDg2ZmQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
         AAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjkyOTk0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
         AAAAAAAAAAAAAAAAAAAAAAAAAAAAAGNmNmFhMmVhMTYwNzRmMjczNjdmZWUyNDg1ZTZkMGM1BwhXVwcIV1c%3DMD;
          phpSESSID=thh4bfrl1t7qre9tr56m32tbv0; 
          Hm_lvt_f0cfcccd7b1393990c78efdeebff3968=1467635471,1467653719,1467654690,1467654957;
           Hm_lpvt_f0cfcccd7b1393990c78efdeebff3968=1467655022; imooc_isnew=2;
            cvde=577a9e57ce250-34",
        "Host":"www.imooc.com",
        "Origin":"http://www.imooc.com",
        "Referer":"http://www.imooc.com/video/8837",
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) 
        AppleWebKit/537.36 (Khtml, like Gecko) Chrome/53.0.2763.0 Safari/537.36",
        "X-Requested-With":"XMLHttpRequest",
    }
}
 
var req=http.request(options,function(res){
    res.on("data",function(chunk){
        console.log(chunk);
    });
    res.on("end",function(){
        console.log("评论完毕!");
    });
    console.log(res.statusCode);
});
 
req.on("error",function(err){
    console.log(err.message);
})
req.write(postData);
req.end();

6. jade module

jade is a high-performance, concise and easy-to-understand template engine. HTML files can be written through jade.

jade is similar to a language for quickly writing HTML, and the suffix of the written file is .jade.

7. Express module

Express is a nodejs web open source framework, used to quickly build web projects. It mainly integrates the creation of web http servers, static text management, server URL address request processing, get and post request processing and distribution, session processing and other functions.

Usage method, open the path of the web project you want to create in cmd. Then enter

Express appname

to create a web project named appname.

[Recommended learning: "nodejs tutorial"]

The above is the detailed content of What are the official modules of nodejs?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to Use useState() Hook in Functional React ComponentsHow to Use useState() Hook in Functional React ComponentsApr 30, 2025 am 12:25 AM

useState allows state to be added in function components because it removes obstacles between class components and function components, making the latter equally powerful. The steps to using useState include: 1) importing the useState hook, 2) initializing the state, 3) using the state and updating the function.

React's View-Focused Nature: Managing Complex Application StateReact's View-Focused Nature: Managing Complex Application StateApr 30, 2025 am 12:25 AM

React's view focus manages complex application state by introducing additional tools and patterns. 1) React itself does not handle state management, and focuses on mapping states to views. 2) Complex applications need to use Redux, MobX, or ContextAPI to decouple states, making management more structured and predictable.

Integrating React with Other Libraries and FrameworksIntegrating React with Other Libraries and FrameworksApr 30, 2025 am 12:24 AM

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

Accessibility Considerations with React: Building Inclusive UIsAccessibility Considerations with React: Building Inclusive UIsApr 30, 2025 am 12:21 AM

TomakeReactapplicationsmoreaccessible,followthesesteps:1)UsesemanticHTMLelementsinJSXforbetternavigationandSEO.2)Implementfocusmanagementforkeyboardusers,especiallyinmodals.3)UtilizeReacthookslikeuseEffecttomanagedynamiccontentchangesandARIAliveregio

SEO Challenges with React: Addressing Client-Side Rendering IssuesSEO Challenges with React: Addressing Client-Side Rendering IssuesApr 30, 2025 am 12:19 AM

SEO for React applications can be solved by the following methods: 1. Implement server-side rendering (SSR), such as using Next.js; 2. Use dynamic rendering, such as pre-rendering pages through Prerender.io or Puppeteer; 3. Optimize application performance and use Lighthouse for performance auditing.

The Benefits of React's Strong Community and EcosystemThe Benefits of React's Strong Community and EcosystemApr 29, 2025 am 12:46 AM

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

React Native for Mobile Development: Building Cross-Platform AppsReact Native for Mobile Development: Building Cross-Platform AppsApr 29, 2025 am 12:43 AM

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Updating State Correctly with useState() in ReactUpdating State Correctly with useState() in ReactApr 29, 2025 am 12:42 AM

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools