dirname & filename

LNSol·2022년 11월 12일
0

Javascript

목록 보기
4/6

No dirname & filename

✅ import { dirname, sep } from 'path'
✅ import { fileURLToPath } from 'url'



Util - getDfName

// 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 };
};

usage

import { getDfName } from '../utils/dfname.js'
const { __dirname, __filename } = getDfName(import.meta.url);

console.log(__dirname);
console.log(__filename);

test

// __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

0개의 댓글