当前位置: 首页 > news >正文

Node.js 开发项目

初始化

npm init## 
npm install 

编辑packege.json 添加,以支持ES6的语法

"type": "module"

连接mysql示例

import db from './db/ops_mysql.js'const createTable = async () => {const insert_data = `CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY,username VARCHAR(255) NOT NULL,password VARCHAR(255) NOT NULL);`;try {await db.query(createTableSQL);console.log('Table `users` created successfully.');} catch (error) {console.error('Error creating table:', error);} finally {await db.end();}
};const insertData = async () => {const insert_data = `INSERT INTO users (username, password) VALUES ('knight', '112233');`;try {await db.query(insert_data);console.log('Data inserted successfully into `users` table.');} catch (error) {console.error('Error inserting data:', error);} finally {await db.end();}
};// createTable();// insertData();

http请求示例

import fetch, { Response } from "node-fetch";
// 发送get请求const fetchData =  async(userid)=>{const url = `https://jsonplaceholder.typicode.com/posts?userId=${userid}`;const res = await fetch(url);// const data = await res.json();/*在你的代码中,res.json() 返回的是一个 Promise 对象,而不是直接的数据。如果你在调用 res.json() 前不加 await,你实际上是在处理一个 Promise,而不是获取到 JSON 数据使用 await:当你在前面加上 await 时,代码会暂停执行,直到 Promise 完成并返回解析后的数据。*/const data =  res.json();   console.log(data)     };fetchData(1)

读取json配置文件

import fs from 'fs/promises';async function loadConfig(){const data  = await fs.readFile('conf/config.json','utf-8');const config = JSON.parse(data);console.log(config);console.log(config.database['host']);}loadConfig();

web框架

import express from 'express';const app = express();const port  = process.env.port || 3000;
console.log(port);app.listen(port,()=>{console.log('....running ');
})app.get('/user',(req,res)=>{res.send({'name':'rose','age':30})
})// 静态资源路径
app.use(express.static('static'));
app.use(express.static('public'));

相关文章:

  • Antd Modal Drawer 更改默认项
  • 【leetcode刷题日记】lc.73-矩阵置零
  • 一些有关ffmpeg 使用(1)
  • Z-Wave正通过自我革新,重塑在智能家居领域新定位
  • [FPGA基础] DMA
  • 0基础 | Proteus仿真 | 51单片机 | 继电器
  • MySQL的MVCC【学习笔记】
  • 01.oracle SQL基础
  • Django之旅:第七节--模版继承
  • IDEA配置将Servlet真正布署到Tomcat
  • Matplotlib高阶技术全景解析(续):动态交互、三维可视化与性能优化
  • 【初识Trae】字节跳动推出的下一代AI原生IDE,重新定义智能编程
  • 微服务架构在云原生后端的深度融合与实践路径
  • 图论---Kruskal(稀疏图)
  • PDFMathTranslate:基于LLM的PDF文档翻译及双语对照的工具【使用教程】
  • Spine 动画教程:皮肤制作
  • 深度学习笔记22-RNN心脏病预测(Tensorflow)
  • Azure Data Factory ETL设计与调度最佳实践
  • 【RedisLockRegistry】分布式锁
  • 抖音小程序开发常见问题与代码解决方案
  • 保时捷中国研发中心落户上海虹桥商务区,计划下半年投入运营
  • 从中央政治局会议看经济工作着力点:以高质量发展的确定性应对外部不确定性
  • 经济日报:上海车展展现独特魅力
  • 鞍钢矿业党委书记、董事长刘炳宇调任中铝集团副总经理
  • 广州多条BRT相关线路将停运,全市BRT客运量较高峰时大幅下降
  • 解码人格拼图:探索心理健康的多维视角