Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS DuckDB + QuickBI 企业套餐,8核32GB + QuickBI 专业版
简介: Node.js【文件系统模块、路径模块 、连接 MySQL、nodemon、操作 MySQL】(三)-全面详解(学习总结---从入门到深化)



Node.js 文件系统模块(二)

打开文件

fs.open(path, flags[, mode], callback)

Flag  描述
以读取模式打开文件。如果文件不存在抛出异常。
r+ 以读写模式打开文件。如果文件不存在抛出异常。
rs  以同步的方式读取文件。
rs+  以同步的方式读取和写入文件。
以写入模式打开文件,如果文件不存在则创建。
wx 类似 'w',但是如果文件路径存在,则文件写入失败。
w+  以读写模式打开文件,如果文件不存在则创建。
wx+  类似 'w+', 但是如果文件路径存在,则文件读写失败。
以追加模式打开文件,如果文件不存在则创建。
ax  类似 'a', 但是如果文件路径存在,则文件追加失败。
a+ 以读写追加模式打开文件,如果文件不存在则创建。
ax+  类似 'a+', 但是如果文件路径存在,则文件读取追加失败。
const fs=require('fs')
fs.open('input.txt', 'r+', function(err, fd)
{
 if (err) {
   return console.error(err);
 } 
  console.log(fd);
  fs.writeFile(fd, '小童程序员', (err) => {
    if(err){
     return  console.log(err)
   }
    console.log('写入完成')
 })
});

Node.js 文件系统模块(三)

查看文件

fs.stat(path, callback)

var fs = require("fs");
fs.stat('input.txt', function (err, stats)
{
 if (err) {
   return console.error(err);
 }
 console.log(stats);
 // 检测文件类型
 console.log("是否为文件 ? " + stats.isFile());
 console.log("是否为目录 ? " + stats.isDirectory());  
});

删除文件

fs.unlink(path, callback)

fs.unlink('input.txt', function(err) {
 if (err) {
   return console.error(err);
 }
 console.log("文件删除成功!");
});

Node.js 文件系统模块(四)

1、创建目录

fs.mkdir(path[, options], callback)

var fs = require("fs");
// tmp 目录必须存在
console.log("创建目录 tmp/test");
fs.mkdir("./tmp/test",function(err){
 if (err) {
   return console.error(err);
 }
 console.log("目录创建成功。");
});
fs.mkdir("./tmp/test",{ recursive: true
},function(err){
  if (err) {
    return console.error(err);
 }
  console.log("目录创建成功。");
});

2、读取目录

fs.readdir(path, callback)

var fs = require("fs");
console.log("查看 /tmp 目录");
fs.readdir("./tmp",function(err, files){
 if (err) {
   return console.error(err);
 }
 files.forEach( function (file){
   console.log( file );
 });
});

3、删除目录

fs.rmdir(path, callback)

var fs = require("fs");
// 执行前创建一个空的 /tmp/test 目录
console.log("准备删除目录 ./tmp/test");
fs.rmdir("./tmp/test",function(err){
 if (err) {
   return console.log(err);
 }
});

提示:

删除目录,如果目录下面有下一级则报错

Node.js 路径模块

path 是Node.js的路径模块,用来处理路径。

path.dirname()

返回路径的目录部分

require('path').dirname('./test/something') // ./test
require('path').dirname('./test/something/file.txt')
// ./test/something

path.extname()

返回路径的扩展名部分

require('path').extname('./test/something') // ''
require('path').extname('./test/something/input.txt') // '.txt'

path.isAbsolute()

如果是绝对路径,则返回 true。

require('path').isAbsolute('/test/something') // true
require('path').isAbsolute('./test/something') // false

path.join()

连接路径的两个或多个部分

const name = '程序员'
require('path').join('/', '小童', name) //'/小童/程序员'

path.parse()

解析对象的路径为组成其的片段:

       root : 根路径。

      dir : 从根路径开始的文件夹路径。

       base : 文件名 + 扩展名

       name : 文件名

       ext : 文件扩展名

require('path').parse('/users/test.txt')
//{
// root: '/',
// dir: '/users',
// base: 'test.txt',
// ext: '.txt',
// name: 'test'
//}

path.relative()

接受 2 个路径作为参数。 基于当前工作目录,返回从第一个路径到第二个路径的相对路径。

require('path').relative('/Users/joe','/Users/joe/test.txt') //'test.txt'
require('path').relative('/Users/joe','/Users/joe/something/test.txt') //'something/test.txt'

path.resolve()

获得相对路径的绝对路径计算

require('path').resolve('joe.txt')
require('path').resolve('/etc', 'joe.txt') //'/etc/joe.txt'

Node.js 连接 MySQL

1、安装MySQL数据库

安装 xampp

       安装包下载地址: https://sourceforge.net/projects/xampp/files/

       进行下载安装

       启动

       新建数据库,新建表

2、安装 mysql

yarn add mysql 或者 npm install mysql

3、node.js 连接 MySQL

var mysql    = require('mysql');
//创建跟数据库的连接
var connection = mysql.createConnection({
 host   : 'localhost',
 user   : 'root',
 password : '',
 database : 'test'
});
//启动连接
connection.connect();
//执行查询
connection.query('select * from test',
function (error, results) {
 if (error) throw error;
 console.log(results);
});

Node.js nodemon

安装 nodemon

yarn add nodemon 或者 npm install nodemon --save

使用nodemon运行脚本

nodemon 脚本文件

使用package.json脚本

"scripts": {
  "start":"nodemon index.js"
}

使用 npx

npx nodemon index.js

Node.js 操作 MySQL

1、查询

connection.query('select * from test where name=?','test1', function (error, results,fields) {
 if (error) throw error;
 console.log(results,'results');
});

2、插入

connection.query('insert into test(name) values (?)','test3', function (error,results, fields) {
  if (error) throw error;
  if(results.affectedRows){
    console.log('插入成功')
 }
});

3、更新

connection.query('update test set value=? where name=?', [10,'test4'], function (error, results, fields) {
  if (error) throw error;
  if (results.affectedRows) {
    console.log('更新成功')
 }
});

4、删除

connection.query('delete from test where name=?', ['test4'], function (error, results, fields) {
  if (error) throw error;
  if (results.affectedRows) {
    console.log('删除成功')
 }
});

Node.js 应用

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 600px;
      margin: 50px auto;
   }
    table {
      width: 100%;
      text-align: center;
   }
   table thead th {
      background-color: #aaa;
   }
    table tbody td {
      background-color: #eee;
      padding: 5px
   }
    form {
      margin-bottom: 50px;
      text-align: center;
   }
    input {
      margin-bottom: 15px;
   }
    button {
      margin-left: 10px
   }
  </style>
</head>
<body>
  <div class="container">
    <!-- 新增数据的表单 -->
    <form id="form1" action="http://localhost:3030/add"  method="post">
      名称:<input type="text"  name="name"><br />
     数量:<input type="text"  name="value"><br />
      <input type="submit" value="提交" />
    </form>
    <!-- 查询数据的输入框 -->
    <input type="text" placeholder="请输入搜索的名称" id="name">
    <button onclick="onGetList()">搜索</button>
    <!-- 展示数据的列表 -->
    <table>
      <thead>
        <th>名称</th>
        <th>数量</th>
        <th>操作</th>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
  <script>
    // 获取数据
    var onGetList = function () {
      // 获取tbody
      var tbody = document.querySelector('tbody')
      // 获取搜索框里面的内容
     const name = document.querySelector('#name').value
      // 发送获取数据的请求
      fetch('/getlist?name=' + name).then(function (data) {
        data.json().then(function (result) {
          tbody.innerHTML = null
          // 遍历返回的数据,生成每一行数据
         result.records.forEach(function (item) {
            var tr = document.createElement('tr')
            tr.innerHTML = '<td>' + item.name + '</td>' + '<td>' + item.value + '</td>'
            var td = document.createElement('td')
            var button = document.createElement('button')
            button.innerHTML = '删除'
            // 点击删除
            button.onclick = function () {
              remove(item)
           }
            td.append(button)
            tr.appendChild(td)
            tbody.appendChild(tr)
         })
       })
     })
   }
    // 删除数据
    function remove(item) {
      // 发送请求,并传递要删除数据的id
      fetch('/remove', { method: 'POST', body: JSON.stringify({ id: item.id }), headers: { 'Content-Type': 'application/json' } }).then(function (data) {
        console.log(data)
        data.json().then(function (result) {
          console.log('成功')
          onGetList()
       })
     })
   }
    window.onload = function () {
      onGetList()
   }
  </script>
</body>
</html>

mysql.js

var mysql = require('mysql');
const sqlConfig = {
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
}
let connection = mysql.createConnection(sqlConfig)
const sqlFn = function (sql, arr, callback)
{
  connection.query(sql, arr, callback)
}
module.exports = sqlFn

server.js

const http=require('http')
const router=require('./router')
http.createServer(function(req,res){
  router(req,res)
}).listen('3030')

router.js

const sqlFn = require('./index')
const url = require('url')
const querystring = require('querystring')
const fs = require('fs')
module.exports = (req, res) => {
  const { pathname, query } = url.parse(req.url, true)
  console.log(req.method)
  if (req.method == 'POST') {
    let params = ''
    req.on('data', (chunk) => {
      params += chunk
   })
    req.on('end', () => {
      console.log(params)
      let postParams = querystring.parse(params)
      if (req.headers['content-type'] == 'application/json') {
        postParams = JSON.parse(params)
     }
      // 处理新增数据的请求
      if (pathname == '/add') {
        sqlFn('insert into test(id,name,value) values (null,?,?) ',[postParams.name, postParams.value], (results) => {
          if (results.affectedRows) {
           res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
           res.end(JSON.stringify({ code: 0, message: '操作成功' }))
         }
       })
     }
      //处理删除请求
      if (pathname == '/remove') {
        console.log(postParams)
        sqlFn('delete from test where id=? ', [postParams.id], (results) => {
          if (results.affectedRows) {
            console.log('删除成功')
            res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
            res.end(JSON.stringify({ code: 0, message: '操作成功' }))
         }
       })
     }
   })
 }
  if (req.method == 'GET') {
    // 处理获取数据请求
    if (pathname == '/getlist') {
      sqlFn(`select * from test where ${query.name ? 'name=?' : 'name is not null'}`, [query.name], (results) => {
        console.log(results)
        res.writeHead(200, { "Content-Type": 'application/json;charset=utf-8' })
        res.write(JSON.stringify({ code: 0, records: results }))
        res.end()
     })
   }
    //处理获取html页面请求
    if (pathname == '/index.html') {
      res.writeHead(200, { "Content-Type": 'text/html;charset=utf8' })
      fs.readFile('./index.html', (err, data) => {
        res.end(data)
     })
   }
 }
}
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
JavaScript 前端开发
在Node.js中,如何合理使用模块来避免全局变量的问题?
在Node.js中,如何合理使用模块来避免全局变量的问题?
610 167
|
SQL JavaScript 关系型数据库
node博客小项目:接口开发、连接mysql数据库
【10月更文挑战第14天】node博客小项目:接口开发、连接mysql数据库
|
缓存 JSON JavaScript
Node.js模块系统
10月更文挑战第4天
172 2
|
SQL JavaScript 关系型数据库
Node.js 连接 MySQL
10月更文挑战第9天
218 0
|
JavaScript 应用服务中间件 Apache
Node.js Web 模块
10月更文挑战第7天
185 0
|
JavaScript 网络协议
Node.js 工具模块
10月更文挑战第7天
172 0
|
JavaScript 前端开发 应用服务中间件
Node.js Web 模块
Node.js Web 模块
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的客户关系管理系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的客户关系管理系统附带文章源码部署视频讲解等
453 2
|
JavaScript 前端开发
JavaScript中的原型 保姆级文章一文搞懂
本文详细解析了JavaScript中的原型概念,从构造函数、原型对象、`__proto__`属性、`constructor`属性到原型链,层层递进地解释了JavaScript如何通过原型实现继承机制。适合初学者深入理解JS面向对象编程的核心原理。
345 1
JavaScript中的原型 保姆级文章一文搞懂
JS+CSS3文章内容背景黑白切换源码
JS+CSS3文章内容背景黑白切换源码是一款基于JS+CSS3制作的简单网页文章文字内容背景颜色黑白切换效果。
221 0

推荐镜像

更多