Nodejs 笔记

    技术2022-07-10  75

    Nodejs 笔记


    event Module const EventEmitter = require('events'); const eventEmitter = new EventEmitter(); //事件监听器 eventEmitter.on('tutorial',(num1,num2)=>{ console.log('tutorial event has occurred'); console.log(num1 + num2); }) //发起tutorial事件 eventEmitter.emit('tutorial',1,2); class Person extends EventEmitter { constructor(name){ super(); this._name = name; } get name(){ return this._name; } } let pedro = new Person('Pedro'); pedro.on('name',()=>{ console.log('My name is ' + pedro.name) }) pedro.emit('name'); readline Module //ReadLine Module的作用是获取用户输入,还能向用户提示程序的输出,即构建用户交互界面。 const readline = require('readline'); const rl = readline.createInterface({input : process.stdin,output : process.stdout}); //Math.random()可以用于生成0-1(不含1)之间的随机数 let num1 = Math.floor(Math.random()*10 + 1); let num2 = Math.floor(Math.random()*10 + 1); let answer = num1 + num2; //rl.question()方法将query写入output,并等待用户在input上提供输入。 //然后调用callback,将用户输入作为回调的第一个参数 rl.question(`What is ${ num1 } + ${ num2 }? \n`,(userInput)=>{ //trim()方法的作用是去掉用户输入(userInput)的前后空格 if(userInput.trim() == answer){ rl.close(); }else{ rl.setPrompt('False Result Please try again.\n'); rl.prompt(); //用户按下回车将触发line事件 rl.on('line',(userInput)=>{ if(userInput.trim() == answer){ rl.close(); }else{ rl.setPrompt(`Your answer ${userInput} is incorrect,please try again.\n`); rl.prompt(); } }) } }); rl.on('close',()=>{ console.log('True'); }); FileSystem Module const fs = require('fs'); //创建文件 fs.writeFile('example.txt','this is a example',(err)=>{ if(err){ console.log('err'); }else{ console.log('File successfully created'); //读取文件 fs.readFile('example.txt','utf8',(err,file)=>{ if(err){ console.log(err); }else{ console.log(file); } }) } }) //重命名文件 fs.rename('example.txt','example2.txt',(err)=>{ if(err){ console.log(err); }else{ console.log('File successfully renamed'); } }) //文件追加内容 fs.appendFile('example2.txt',', Some data been appended',(err)=>{ if(err){ console.log(err); }else{ console.log('File successfully appended.'); } }) //删除文件 fs.unlink('example2.txt',(err)=>{ if(err){ console.log(err); }else{ console.log('File successfully deleted.'); } }) //创建文件夹 fs.mkdir('tutorial',(err)=>{ if(err){ console.log(err); }else{ console.log('folder successfully created'); } }) //删除文件夹(只对空文件夹有效) fs.rmdir('tutorial',(err)=>{ if(err){ console.log(err); }else{ console.log('folder successfully deleted'); } }) //创建文件夹的同时创建文件 fs.mkdir('tutorial',(err)=>{ if(err){ console.log(err); }else{ console.log('folder successfully created'); //注:这里的./表示js文件所在目录 fs.writeFile('./tutorial/example.txt','12345678',(err)=>{ if(err){ console.log(err); }else{ console.log('file successfully created') } }) } }) //读取文件夹,遍历删除文件 fs.readdir('tutorial',(err,files)=>{ if(err){ console.log(err); }else{ console.log(files); for(let file of files){ fs.unlink('./tutorial/'+file,(err)=>{ if(err){ console.log(err); }else{ console.log(`successfully deleted the file ${file}`); } }) } } }) 流式读取文件 const fs = require('fs'); //普通读取文件的方式会将整个文件读入内存缓冲区,如果文件过大将无法读取 //流式读取文件,不用等待文件完全加载即可操作,而是把文件分成小块进行缓冲 //效率更高,对内存需求少。 const readStream = fs.createReadStream('./example.txt','utf8'); const writeStream = fs.createWriteStream('./example2.txt'); //读取文件时将触发data事件,chunk指分块的文件。 readStream.on('data',(chunk)=>{ console.log(chunk); writeStream.write(chunk); console.log('文件写入成功!') });

    注:以上内容和以下内容等价

    const fs = require('fs'); const readStream = fs.createReadStream('./example.txt','utf8'); const writeStream = fs.createWriteStream('./example2.txt'); //管道操作,源头.pipe(目的) readStream.pipe(writeStream); 压缩和解压 //压缩 const fs = require('fs'); const zlib = require('zlib'); const readStream = fs.createReadStream('./example.txt','utf8'); const writeStream = fs.createWriteStream('./example2.gz'); const gzip = zlib.createGzip(); readStream.pipe(gzip).pipe(writeStream); //解压 const fs = require('fs'); const zlib = require('zlib'); const readStream = fs.createReadStream('./example2.gz'); const writeStream = fs.createWriteStream('./uncompressed.txt'); const gunzip = zlib.createGunzip(); readStream.pipe(gunzip).pipe(writeStream); http Module const http = require('http'); //req参数就是浏览器发送来的请求, const server = http.createServer((req,res)=>{ if(req.url === '/'){ res.write('Hello BLU from node.js'); //调用res.end()方法才会真正返回响应! res.end(); }else{ res.write('use some other domain'); res.end(); } }); //监听3000端口 server.listen('3000'); 静态资源托管 const http = require('http'); const fs = require('fs'); http.createServer((req,res)=>{ const readStream = fs.createReadStream('./static/baidu.png'); res.writeHead(200,{'Content-type':'image/png'}); readStream.pipe(res); }).listen(3000); const http = require('http'); const fs = require('fs'); http.createServer((req,res)=>{ const readStream = fs.createReadStream('./static/index.html'); res.writeHead(200,{'Content-type':'text/html'}); readStream.pipe(res); }).listen(3000); const http = require('http'); const fs = require('fs'); http.createServer((req,res)=>{ const readStream = fs.createReadStream('./static/example.json'); res.writeHead(200,{'Content-type':'application/json'}); readStream.pipe(res); }).listen(3000); npm init

    npm init 可用来初始化生成一个新的 package.json 文件:

    { "name": "src", "version": "1.0.0", "description": "BLU", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "BLU", "license": "ISC", "dependencies": {} } npm install

    npm install 命令用来安装模块 示例:

    npm install lodash
    Processed: 0.013, SQL: 9