Node.js를 사용하여 현재 스크립트의 경로를 어떻게 얻습니까?
Node.js에서 스크립트 경로를 어떻게 얻습니까?
나는 거기에 있다는 것을 알고 process.cwd있지만 그것은 스크립트 자체가 아니라 스크립트가 호출 된 디렉토리만을 나타냅니다. 예를 들어, I 'm in이라고 말하고 /home/kyle/다음 명령을 실행합니다.
node /home/kyle/some/dir/file.js
내가 전화 process.cwd()하면, 나는받지 /home/kyle/않는다 /home/kyle/some/dir/. 그 디렉토리를 얻는 방법이 있습니까?
문서를 다시 살펴본 후에 찾았습니다. 내가 찾고 있던 것은 __filename및 __dirname모듈 수준 변수였습니다.
__filename현재 모듈의 파일 이름입니다. 현재 모듈 파일의 확인 된 절대 경로입니다. (예 :/home/kyle/some/dir/file.js)__dirname현재 모듈의 디렉토리 이름입니다. (예 :/home/kyle/some/dir)
따라서 기본적으로 이렇게 할 수 있습니다.
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
'/'또는 '\'와 연결하는 대신 resolve ()를 사용하십시오. 그렇지 않으면 플랫폼 간 문제가 발생합니다.
참고 : __dirname은 모듈 또는 포함 된 스크립트의 로컬 경로입니다. 메인 스크립트의 경로를 알아야하는 플러그인을 작성하는 경우 다음과 같습니다.
require.main.filename
또는 폴더 이름을 얻으려면 :
require('path').dirname(require.main.filename)
이 명령은 현재 디렉토리를 반환합니다.
var currentPath = process.cwd();
예를 들어, 경로를 사용하여 파일을 읽으려면 :
var fs = require('fs');
fs.readFile(process.cwd() + "\\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
__dirname !! 사용
__dirname
현재 모듈의 디렉토리 이름입니다. 이것은의 path.dirname ()과 동일합니다 __filename.
예 : / Users / mjr에서 node example.js 실행
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
ESModules의 경우 다음을 사용합니다. import.meta.url
메인 스크립트에 관해서는 다음과 같이 간단합니다.
process.argv[1]
로부터 Node.js를 문서 :
process.argv
명령 줄 인수를 포함하는 배열입니다. 첫 번째 요소는 'node'이고 두 번째 요소는 JavaScript 파일의 경로 입니다. 다음 요소는 추가 명령 줄 인수입니다.
모듈 파일의 경로를 알아야하는 경우 __filename 을 사용 하십시오 .
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
모든 Node.js 프로그램에는 프로세스에 대한 일부 정보를 나타내는 일부 전역 변수가 환경에 있으며 그중 하나는 __dirname.
10 개 지원 Node.js를 ECMAScript를 모듈 , __dirname그리고 __filename더 이상 사용할 수 있습니다 .
그런 다음 현재 ES 모듈 의 경로 를 얻으려면 다음을 사용해야합니다.
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
그리고 현재 모듈을 포함하는 디렉토리의 경우 :
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
You can use process.env.PWD to get the current app folder path.
If you are using pkg to package your app, you'll find useful this expression:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
process.pkgtells if the app has been packaged bypkg.process.execPathholds the full path of the executable, which is/usr/bin/nodeor similar for direct invocations of scripts (node test.js), or the packaged app.require.main.filenameholds the full path of the main script, but it's empty when Node runs in interactive mode.__dirnameholds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));noting that in interactive mode__dirnameis empty.For interactive mode, use either
process.argv[0]to get the path to the Node executable orprocess.cwd()to get the current directory.
Use the basename method of the path module:
var path = require('path');
var filename = path.basename(__filename);
console.log(filename);
Here is the documentation the above example is taken from.
As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname and __filename as above.
If you are using the --experimental-modules flag, there is an alternative approach.
The alternative is to get the path to the current ES module:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
If you want something more like $0 in a shell script, try this:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
참고URL : https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js
'code' 카테고리의 다른 글
| JDK (JNI 공유 라이브러리)를로드하지 못했습니다. (0) | 2020.09.28 |
|---|---|
| 이벤트를 발생시킨 요소의 ID 가져 오기 (0) | 2020.09.28 |
| 여러 열로 그룹화 (0) | 2020.09.28 |
| Bootstrap 열을 모두 같은 높이로 만들려면 어떻게해야합니까? (0) | 2020.09.28 |
| NSString 값을 NSData로 어떻게 변환합니까? (0) | 2020.09.28 |