nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.45k stars 278 forks source link

Node not finding a file after migrating my application to TypeScript #4251

Closed ThomPoppins closed 9 months ago

ThomPoppins commented 9 months ago

Details

After rewriting my Express.js application to TypeScript, the application can't find a certificate path anymore.

I think this is an error caused by node trying first compiling to #JavaScript and that Javascript isn't in a relative location to the file.

2023-09-24 14_16_37-package json - MERN-stack-TypeScript-project - Visual Studio Code 2023-09-24 14_29_34-kvkRoute ts - MERN-stack-TypeScript-project - Visual Studio Code

What to do? What is the filepath the file needs to be placed at for the TypeScript application to find it?

Node.js version

v16.20.1

Example code

import express from "express"; import fs from "fs"; import axios from "axios"; import https from "https"; import cors from "cors"; import { fileURLToPath } from "url"; import path from "path"; import { KVK_TEST_API_KEY } from "../config.js";

const PATH_TO_KVK_API_CERTIFICATE_CHAIN_RELATIVE_TO_INDEX_APP = "./certs/kvkApi/Private_G1_chain.pem";

const router = express.Router();

// Route to get data from the KVK API // Route to get one user from database using the user's id router.get("/", async (request, response) => { try { // Get the query from the request query parameters const { kvkNumber } = request.query;

// Get the certificate chain from the file system
const certificateChain = fs.readFileSync(
  PATH_TO_KVK_API_CERTIFICATE_CHAIN_RELATIVE_TO_INDEX_APP,
  "utf8"
);

const agent = new https.Agent({
  ca: certificateChain,
});

// Get the data from the KVK API
const { data } = await axios.get(
  `https://api.kvk.nl/test/api/v1/naamgevingen/kvknummer/${kvkNumber}`,
  {
    headers: {
      apikey: KVK_TEST_API_KEY,
    },
    httpsAgent: agent,
  }
);

// Send status 200 response and the data to the client
return response.status(200).json(data);

} catch (error) { console.log("Error in GET /kvk: ", error); if (error.response.status === 400) { response.status(400).send({ message: error.message }); } else { response.status(500).send({ message: error.message }); } } });

export default router;

// ERROR MESSAGE: // Error: ENOENT: no such file or directory, open './certs/kvkApi/Private_G1_chain.pem'

Operating system

Windows 11

Scope

TypeScript, file, path

Module and version

"fs": "^0.0.1-security",

ljharb commented 9 months ago

Note that fs is a core module and shouldn’t be installed from npm (this is unrelated to your problem)

mcollina commented 9 months ago

This is pretty normal for TypeScript. I'm not exactly sure how your application is compiled and where the files are loaded from, but if they do from dist/ or similar, that specific path would change. I recommend using a path relative to the current file, e.g. join(__dirname, ..).