|
4 | 4 | #include "env-inl.h"
|
5 | 5 | #include "memory_tracker-inl.h"
|
6 | 6 | #include "node.h"
|
| 7 | +#include "node_dotenv.h" |
7 | 8 | #include "node_errors.h"
|
8 | 9 | #include "node_external_reference.h"
|
9 | 10 | #include "node_internals.h"
|
@@ -463,6 +464,38 @@ static void ReallyExit(const FunctionCallbackInfo<Value>& args) {
|
463 | 464 | env->Exit(code);
|
464 | 465 | }
|
465 | 466 |
|
| 467 | +static void LoadEnvFile(const v8::FunctionCallbackInfo<v8::Value>& args) { |
| 468 | + Environment* env = Environment::GetCurrent(args); |
| 469 | + std::string path = ".env"; |
| 470 | + if (args.Length() == 1) { |
| 471 | + Utf8Value path_value(args.GetIsolate(), args[0]); |
| 472 | + path = path_value.ToString(); |
| 473 | + } |
| 474 | + |
| 475 | + THROW_IF_INSUFFICIENT_PERMISSIONS( |
| 476 | + env, permission::PermissionScope::kFileSystemRead, path); |
| 477 | + |
| 478 | + Dotenv dotenv{}; |
| 479 | + |
| 480 | + switch (dotenv.ParsePath(path)) { |
| 481 | + case dotenv.ParseResult::Valid: { |
| 482 | + dotenv.SetEnvironment(env); |
| 483 | + break; |
| 484 | + } |
| 485 | + case dotenv.ParseResult::InvalidContent: { |
| 486 | + THROW_ERR_INVALID_ARG_TYPE( |
| 487 | + env, "Contents of '%s' should be a valid string.", path.c_str()); |
| 488 | + break; |
| 489 | + } |
| 490 | + case dotenv.ParseResult::FileError: { |
| 491 | + env->ThrowUVException(UV_ENOENT, "Failed to load '%s'.", path.c_str()); |
| 492 | + break; |
| 493 | + } |
| 494 | + default: |
| 495 | + UNREACHABLE(); |
| 496 | + } |
| 497 | +} |
| 498 | + |
466 | 499 | namespace process {
|
467 | 500 |
|
468 | 501 | BindingData::BindingData(Realm* realm,
|
@@ -616,6 +649,8 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
|
616 | 649 | SetMethod(isolate, target, "reallyExit", ReallyExit);
|
617 | 650 | SetMethodNoSideEffect(isolate, target, "uptime", Uptime);
|
618 | 651 | SetMethod(isolate, target, "patchProcessObject", PatchProcessObject);
|
| 652 | + |
| 653 | + SetMethod(isolate, target, "loadEnvFile", LoadEnvFile); |
619 | 654 | }
|
620 | 655 |
|
621 | 656 | static void CreatePerContextProperties(Local<Object> target,
|
@@ -653,6 +688,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
|
653 | 688 | registry->Register(ReallyExit);
|
654 | 689 | registry->Register(Uptime);
|
655 | 690 | registry->Register(PatchProcessObject);
|
| 691 | + |
| 692 | + registry->Register(LoadEnvFile); |
656 | 693 | }
|
657 | 694 |
|
658 | 695 | } // namespace process
|
|
0 commit comments