博客
关于我
next项目部署到服务器pm2进程守护
阅读量:791 次
发布时间:2023-02-15

本文共 2037 字,大约阅读时间需要 6 分钟。

一、npm run export导出文件上传到CDN

在项目中执行npm run export后,会生成outCDN文件夹。接下来需要将该文件夹中的文件上传至CDN服务器。

以下是上传文件的具体实现代码:

```javascriptconst fs = require('fs');const path = require('path');const OSS = require('ali-oss');const filePath = path.join(__dirname, '../outCDN');const excludeFiles = ['index.html'];

const client = new OSS({region: 'oss-cn-shenzhen',accessKeyId: '',accessKeySecret: '',bucket: ''});

async function uploadFile(filePath) {fs.readdir(filePath, async function(err, files) {if (err) {console.warn('读取文件失败:%s', err);} else {files.forEach(async function(filename) {const filedir = path.join(filePath, filename);fs.stat(filedir, async function(err, stats) {if (err) {console.warn('获取文件stats失败:%s', err);} else {const isFile = stats.isFile();const isDir = stats.isDirectory();if (!excludeFiles.includes(filename) && isFile) {const fileKey = ${filedir.split('outCDN/').pop()};try {const data = await client.put(fileKey, filedir);console.log('上传成功:%j', data);} catch (err) {console.error('上传失败:%j', err);}}if (isDir) {uploadFile(filedir);}}});});}});}

uploadFile(filePath);

二、处理next build后的文件

Next.js项目中,执行next build后,会自动生成.next文件夹及其子文件。我们需要将这些文件进行归档和管理,以便后续部署。

归档文件的具体实现代码如下:

```javascriptconst fs = require('fs');const path = require('path');const includeFiles = ['package.json', 'server.js', 'next.config.js', 'ecosystem.json'];async function copyFiles(srcDir) { return new Promise((resolve, reject) => { fs.readdir(srcDir, async function(err, files) { if (err) { reject(err); return; } files.forEach(function(filename) { const currentPath = path.join(srcDir, filename); const stat = fs.statSync(currentPath); if (includeFiles.includes(filename)) { const targetPath = path.join('copiedFiles', filename); fs.createReadStream(currentPath).pipe(fs.writeSync(targetPath)); } else if (stat.isDirectory()) { copyFiles(currentPath); } }); resolve({ success: true }); }); });}copyFiles('src');

上述代码实现了文件的递归复制功能,适用于管理Next.js项目的构建文件。

转载地址:http://lxcfk.baihongyu.com/

你可能感兴趣的文章
Mysql索引总结
查看>>
Mysql缓存调优的基本知识(附Demo)
查看>>
mysql自增id超大问题查询
查看>>
MySQL设置远程连接
查看>>
mysql还有哪些自带的函数呢?别到处找了,看这个就够了。
查看>>
mysql进阶 with-as 性能调优
查看>>
Mysql连接时报时区错误
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
mysql部署错误
查看>>
MySQL锁与脏读、不可重复读、幻读详解
查看>>
Mysql锁机制,行锁表锁
查看>>
MySQL集群解决方案(4):负载均衡
查看>>
mysql面试题学校三表查询_mysql三表查询分组后取每组最大值,mysql面试题。
查看>>
Mysql面试题精选
查看>>
MySQL面试题集锦
查看>>
mysql颠覆实战笔记(八)--mysql的自定义异常处理怎么破
查看>>
mysql驱动、durid、mybatis之间的关系
查看>>
mysql驱动支持中文_mysql 驱动包-Go语言中文社区
查看>>
MySQL高可用切换_(5.9)mysql高可用系列——正常主从切换测试
查看>>
MySQL高可用解决方案详解
查看>>