Node.js从入门到放弃(二)

Node.js从入门到放弃(二)

前言

这是该系列文章的第二篇,主要介绍Node.js的安装,开发流程,模块系统

安装

下载地址

  • https://nodejs.org/en/

  • 根据实际情况选择适合自己电脑的Node版本,注意选择稳定版[LTS],目前最新稳定版是12.14.1

安装流程

注意,Node支持高版本覆盖低版本
如果你电脑已经安装过Node高版本(如13),使用12版本的无法直接安装,需要卸载高版本后重装。
windows系统,整个安装过程傻瓜式安装即可

linux系统,以Ubuntu为例 (先安装后升级)

  • sudo apt-get install nodejs
  • sudo apt-get install npm
  • sudo npm install npm -g
  • npm install –g n
  • n stable //升级node.js到最新稳定版

安装检测

  • 终端输入node -v ,显示版本号则表示安装成功,之后就可以愉快的使用Node.js进行开发了

开发流程

Node.js可以简单理解为js解释器,浏览器让js可以跑在客户端,Node.js让js可以跑在服务端。所以,写好的js代码,直接运行就好了.

扫描二维码关注公众号,回复: 8608314 查看本文章

hello world

//新建一个js文件,名称可自定义,这里就叫app.js
// 写点代码
// 终端运行 node app.js
console.log("hello world")

此时你会发现终端打印出了hello world,并且光标返回,这意味着本次运行结束。值得注意的是,代码如果有改动,需要打断重新运行才会执行最新代码

热更新

  • 更多时候,我们需要对程序进行监听,如果代码有改动,就自动重启,这个时候nodemon 就登场了
  • 全局安装:npm i nodemon -g
  • 启动:nodemon 和node启动方式一样,nodemon app.js ,此时就是热更新了

模块系统

http

如果仅仅是打印级别的开发,实在是无趣。Node.js内置的http模块,可以让你真正体验一把分分钟搭建一个服务器的感觉,这里只进行简单的介绍,真正的服务器搭建都是依赖框架的(express,koa2,egg)
使用http模块快速搭建服务器

//引入核心模块http

var http = require("http");

//创建服务器

var server = http.createServer(function (request, response) {
    response.end("hello world");
});

//运行服务器,监听3000端口(端口号可以任改,业内推荐3000+)

server.listen(3000, function () {

    //打开浏览器,127.0.0.1:3000查看结果

    console.log("服务器启动成功...");
});

fs模块

涉及到IO处理的,基本都会用到fs模块,读写,拷贝,遍历文件夹…,Node大部分都是异编程,但fs模块,基本都支持同步编写。readFile(异步),readFileSync(同步)

//文件读取
  var fs = require('fs')   
    fs.readFile('./a.txt', function (error, data) {
          if (error) {
            console.log('读取文件失败')
          } else {
            console.log(data.toString());//读取结果是二进制,要转化成我们认识的
          }
    })
//文件写入
    var fs = require('fs')
    fs.writeFile('./a.txt', '冷月心', function (error) {
      if (error) {
        console.log('写入失败');
      } else {
        console.log('写入成功');
      }
    })
//遍历文件夹
const fs = require('fs');
const path = require('path');
const folderPath = path.resolve('./testFolder');//指定要遍历的文件夹路径

const cycleFolder = (folderPath) => {
    //根据指定要遍历的文件夹路径,返回文件列表数组,保存在files中
    fs.readdir(folderPath, (err, files) => {
        if (err) throw err;
        files.forEach(filename => {  //遍历读取到的文件列表数组
            const absolutePath = path.join(folderPath, filename);  //获取当前文件的绝对路径
            //根据 fs.stat方法,返回一个提供有关文件的信息fs.Stats对象
            fs.stat(absolutePath, (err, stats) => {
                if (err) throw err;
                const flag = stats.isDirectory();//文件夹递归遍历,文件直接输出绝对路径
                flag ? cycleFolder(absolutePath) : console.log(absolutePath);
            })
        });
    });
}

//调用文件夹遍历方法
cycleFolder(folderPath)

path模块

path模块用于路径解析和处理,比如获取扩展名,文件名,路径拼接…

//文件名处理
//获取自定义格式的文件名

const path = require('path');
const getFileName = (filepath, type = 1) => {
    let result = '';
    if (type === 1) {
        result = path.basename(filepath);
    } else if (type === 2) {
        result = path.extname(filepath);
    } else {

        let basename = path.basename(filepath);
        let extname = path.extname(filepath);
        result = basename.substring(0, basename.indexOf(extname));
    }
    return result;
}



// console.log(getFileName("./date.js", 1))//date.js
// console.log(getFileName("./date.js", 2))//.js
// console.log(getFileName("./date.js", 3))//date

os模块

顾名思义,和操作系统相关的,不太常用

var os = require('os')

// 获取当前机器的 CPU 信息

console.log(os.cpus())

// memory 内存
console.log(os.totalmem())

其他核心模块

zlib(解压缩),dns(域名解析),crypto(加密)…

文件模块

自定义的js文件都属于文件模块,上一篇文章有提到,使用exports和module.exports导出,require导入,不再赘述

第三方模块

通过npm 安装的都属于第三方模块,引入方式与核心模块一致

//文件夹压缩
// 安装 npm i compressing
const compressing = require('compressing');

//folder为自定义要压缩的文件夹

compressing.zip.compressDir(folder, folder+'.zip')
.then(() => {
    console.log('ok');
})
.catch(err => {
    console.log(err);
    return
});

发布了450 篇原创文章 · 获赞 787 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_42813491/article/details/103952618