No dirname & filename
✅ import { dirname, sep } from 'path'
✅ import { fileURLToPath } from 'url'
// utils/dfname.js
import { dirname, sep } from 'path';
import { fileURLToPath } from 'url';
export const getDfName = (imu) => {
const __dirname = dirname(fileURLToPath(imu));
const filePathArr = fileURLToPath(imu).split(sep);
// const __filename = filePathArr[filePathArr.length - 1];
const __filename = filePathArr.at(-1);
return { __dirname, __filename };
};
import { getDfName } from '../utils/dfname.js'
const { __dirname, __filename } = getDfName(import.meta.url);
console.log(__dirname);
console.log(__filename);
// __tests__/tt1.test.js
import { getDfName } from '../utils/dfname.js';
describe('dir&file name', () => {
test('dirname', () => {
const { __dirname } = getDfName(import.meta.url);
expect(__dirname).toBe('/Users/lns/Documents/SeSAC/__test__');
});
test('filename', () => {
const { __filename } = getDfName(import.meta.url);
expect(__filename).toBe('tt1.test.js');
});
});
✅ dirname(import.meta.url)
file:///Users/lns/Documents/SeSAC/node/examples
✅ dirname(fileURLToPath(import.meta.url)
/Users/lns/Documents/SeSAC/node/examples
✅ import.meta.url
file:///Users/lns/Documents/SeSAC/node/examples/tt1_nodeutils.js
✅ fileURLToPath(import.meta.url);
/Users/lns/Documents/SeSAC/node/examples/tt1_nodeutils.js