Skip to content

Instantly share code, notes, and snippets.

@petrosmm
Created February 16, 2023 03:16
Show Gist options
  • Save petrosmm/d76ca51b2ee489c0fdcd6f4dba07671a to your computer and use it in GitHub Desktop.
Save petrosmm/d76ca51b2ee489c0fdcd6f4dba07671a to your computer and use it in GitHub Desktop.
nextjs route searcher
#!/usr/bin/env node
// route searcher with some custom params (...page..., ...api... etc) for next.js
import klaw from "klaw";
import * as fs from 'fs'; // OR const fs = require('fs').promises;
import path from "path";
import * as _fs from 'fs'; // OR const fs = require('fs').promises;
function errorsss(err: NodeJS.ErrnoException | null) {
if (err) {
if (err.errno == -4058) {
return;
} else {
return console.error(err);
}
}
if (false)
console.log("File created!");
}
export const main = async (): Promise<void> => {
if (true)
console.log('__dirname', '../' + process.cwd());
const dir = './pages'
var basePath = path.normalize(process.cwd() + '\\' + dir);
var piecesRoot = basePath.split('\\');
if (false) {
const files = fs.readdirSync(dir)
for (const file of files) {
console.log(file)
}
}
var files = [];
var folders = [];
for await (const file of klaw(dir)) {
// rules
if (file.stats.isFile()
&& file.path.includes('.page.')
&& !file.path.includes('[slug]')
&& !file.path.includes('\\protected\\')
) {
// rules
let _path = file.path.split("\\")
let _fileName = _path[_path.length - 1];
if (!_fileName.startsWith('_')
&& !_fileName.includes('...')) {
let result = file.path;
let folder = path.dirname(result);
files.push(result);
folders.push(folder);
}
}
}
folders = [...new Set(folders)];
if (true) {
console.log('\r\n');
console.log(files);
console.log('\r\n');
console.log(basePath);
}
folders.forEach(p => {
let folderName = path.basename(p);
let pieces = p.split('\\');
let piecesDifference = pieces.length - piecesRoot.length;
if (piecesDifference > 0) {
console.log(`${piecesRoot.length}/${pieces.length} for ${folderName}`);
process.chdir(p);
console.log(`current directory: ${process.cwd()}`);
console.log('\r\n');
if (true) {
// remove this in every directory
let fileName = 'foldername.ts';
_fs.rm(fileName, errorsss);
let line = `export const folderName = "${folderName}";
\r\n
export const level${piecesDifference}_folderName = "${folderName}";`;
console.log(line);
if (false)
fs.writeFile(fileName, line, errorsss);
}
}
});
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment