http module and FS module

First we need to know how to run our node project

Just open a js file and enter node xxx.js (xxx is the name of the js file ) in the terminal (cmd) location of the js.

Not much nonsense, go directly to the code, a total of three steps

//1. Refer to the http module (this module is a system module)
const http = require('http');     
// Second, create a server
var server = http.createServer(function(req,res){ //req request res response
    switch(req.url){
        case '/1.html':
            res.write('111'); //The output will be output in the browser
            break;
        case '/2.html':
            res.write('222');
            break;
        default:
            res.write('404')
            break;
    }
    res.end();
});
//Three, listen port (here I choose 8080, we can choose any port)
server.listen(8080);
run node
Then enter localhost:8080 localhost:8080/1.html in the browser localhost:8080/2.html



FS module————File System Mainly used for file operations
Read file fs.readFile(filename, callback function)
Write file fs.writeFile(filename, content, callback function)
Go directly to the two simplest demos

// refer to the fs module
const fs = require('fs');
 
// 读文件  fs.readFile(文件名,回调函数)
fs.readFile('aaa.txt',function(err,data){
    if(err){
        console.log("读取失败");        
    }else{
        console.log(data)       //正常的出来是2进制的
        console.log(data.toString())
    }
})

// 写文件  fs.writeFile(文件名,内容,回调函数)
fs.writeFile("bbb.txt","ssssss",function(err){
    console.log(err);
})

打个广告:淘宝天猫内部优惠群,加我微信拉你进群18801014156

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325622157&siteId=291194637