Error in Javascript: unable to locate the imported module

When attempting to import the 'CryptographyClient' module from a specified directory, I encountered an issue. Initially successful in typescript, but after compiling the code into javascript, an error was thrown stating that it could not find the module. Below is my original typescript code:

import { CryptographyClient } from "C:/Users/fredg/Desktop/AzureSDK-master/AzureSDK-master/Node/sample/node_modules/@azure/keyvault-keys/src/cryptographyClient";
import { DefaultAzureCredential } from "@azure/identity";
import * as crypto from 'crypto';

async function main(): Promise<void> {
  // DefaultAzureCredential requires these three environment variables:
  // - AZURE_TENANT_ID: Azure Active Directory tenant ID
  // - AZURE_CLIENT_ID: Application (client) ID registered with AAD
  // - AZURE_CLIENT_SECRET: Client secret for registered application
  const credential = new DefaultAzureCredential();

  const vaultName = process.env["KEYVAULT_NAME"] || "keyvault-js"
  const url = `https://${vaultName}.vault.azure.net`;

  // Establishing connection with Azure Key Vault
  const client = new KeysClient(url, credential);

  let keyName = "localWorkKey";

  // Connecting to Azure Key Vault Cryptography features
  let myWorkKey = await client.createKey(keyName, "RSA");

  const cryptoClient = new CryptographyClient(url, myWorkKey.keyMaterial!.kid!, credential);

  // Sign and Verify operations
  const signatureValue = "MySignature";
  let hash = crypto.createHash("sha256");

  hash.update(signatureValue);
  let digest = hash.digest();
  console.log("digest: ", digest);

  const signature = await cryptoClient.sign("RS256", digest);
  console.log("sign result: ", signature);

  const verifyResult = await cryptoClient.verify("RS256", digest, signature.result);
  console.log("verify result: ", verifyResult);

  // Encrypt and decrypt data
  const encrypt = await cryptoClient.encrypt("RSA1_5", Buffer.from("My Message"));
  console.log("encrypt result: ", encrypt);

  const decrypt = await cryptoClient.decrypt("RSA1_5", encrypt.result);
  console.log("decrypt: ", decrypt.result.toString());

  // Wrap and unwrap keys
  const wrapped = await cryptoClient.wrapKey("RSA-OAEP", Buffer.from("My Message"));
  console.log("wrap result: ", wrapped);

  const unwrapped = await cryptoClient.unwrapKey("RSA-OAEP", wrapped.result);
  console.log("unwrap result: ", unwrapped);

  await client.deleteKey(keyName);
}
main().catch((err) => {
  console.log("error code: ", err.code);
  console.log("error message: ", err.message);
  console.log("error stack: ", err.stack);
});

Although I anticipated smooth execution of the code, an error message appeared in the terminal:

Error: Cannot find module 'C:/Users/fredg/Desktop/AzureSDK-master/AzureSDK-master/Node/sample/node_modules/@azure/keyvault-keys/src/cryptographyClient'

Answer №1

To solve this issue, try utilizing relative imports rather than absolute ones. Simply import from the specified package:

import { CryptographyClient } from "@azure/keyvault-keys";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the radio button not chosen in the ns-popover popup? The radio button is only selected in the popup of the last column

In my Angular controller, I am trying to set the radio model but it is only appearing in the last column popup of the table. The ns-popover is displayed when clicking on a table column. Here is the Angular Code: var app = angular.module('app', ...

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

What is the best way to transfer data received from a controller to Express' router?

Seeking assistance in creating a versatile function to handle data retrieval for my Author endpoint. The goal is to return a complete list of authors if the URL passed to the endpoint has no query parameters. If the URL includes firstName and lastName para ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...

Retrieve the array element that is larger than the specified number, along with its adjacent index

Consider the following object: const myObject = { 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, }; Suppose we also have a number, let's say 25. Now, I want to iterate over the myObject using Object.entries(myObject), and obtain a specific result. For ...

Multiple 'keydown' events are accumulating with Ajax activated

When the search field is focused, I am loading JSON into the browser and then iterating over the JSON objects to find real-time results 'on keydown'. The issue I'm encountering is detailed in the console after the initial block of code Aja ...

Angular and dropdowns: a perfect match

Imagine having a controller like this: myApp.controller('testCtrl', function ($scope) { $scope.cars = [ { carId: '1', carModel: 'BMW', carOwner: 'Nader' }, { carId: '2', carModel: &apos ...

Functions designed to facilitate communication between systems

There is an interface that is heavily used in the project and there is some recurring logic within it. I feel like the current solution is not efficient and I am looking for a way to encapsulate this logic. Current code: interface Person { status: Sta ...

Error: Unable to access the 'create' property of an undefined value

I'm currently working on a website that utilizes Passport.js for user management. Despite being able to run my server, I encounter an issue when a user tries to submit their signup details which results in the error message "TypeError: Cannot read pro ...

Send a Dictionary<String,List<String>> over to a JavaScript array

Welcome to my web service! [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Dictionary<string,List<string>> GetCategorias() { var diccionario = new Dictionary<string, List<string>>(); var categoria = ...

Exporting from Blender to three.js can sometimes result in misaligned object positions

Currently, I am encountering a challenge while exporting a basic scene from Blender to Three.js. Apart from the ongoing struggle with the texture not displaying properly, I have discovered an odd issue with the positioning of objects. The image below showc ...

What steps should I take to fix the following error: TypeError: undefined is not an object when trying to evaluate '_bip.default.generateMnemonic'?

I'm in the process of developing a mobile application and I find myself in need of utilizing bip39 for passphrase generation. However, after installing the necessary package, I encountered errors related to missing packages like stream buffer events. ...

Allow JavaScript to determine whether to link to an internal or external web address

Currently, I am in the process of setting up a new website and need to create an HTML page with some JavaScript that can determine whether to link to the external or internal IP address. I have researched some JavaScript code to fetch the IP address, whic ...

The URL cannot be retrieved using an Ajax call, but it is accessible through Postman

I'm having trouble fetching the URL "" using $.get. Strangely, when I paste the exact same URL into Postman, it works perfectly. Visit my JSFiddle page for reference. $.get( "https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/album", ...

Unprepared for handling JSON data with JavaScript and jQuery

{ "Items": [ { "location": "bakery", "item1": "milk", "item2": "bread" } ], } Currently, I am encountering difficulties in parsing a JSON object and receiving the following error: Error: Unca ...

What is the most efficient way to switch perspectives?

I'm currently utilizing storybook to simulate various pages of my application. My concept involves encapsulating storybook within one context for mock data, and then during live application execution, switching to a different context where data is fet ...

I'm running into an issue where I am unable to retrieve a variable from a separate

Struggling to populate a dropdown menu as I keep encountering an undefined error for all currencies when trying to reference them. A third party provided me with this code to simply fill the dropdown and make some text edits, but I'm puzzled as to wh ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

Issue encountered when sorting sequelize query by date in ascending sequence

My challenge is to arrange a sequelize query in ascending order by date. Specifically, I am focusing on sorting the results of the model: ExamScore (referred to as student_score). I've specified the column "updated_at" for ordering and the method of ...