Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
Using Path Module in NODE.JS

I'm trying to store the absolute path of a file in a variable, exporting it through module.exports to use it in other files, for example, a file in another project folder, accessing it by require. After that, I use this variable as the path of the readFileSync method. Very well, when running the code in V.S Code, it works perfectly, but when I try to run it in the terminal, the path that appears is different! Why does it happen?

//path_module.js file code (located in 'path' folder):

const testPath = path.resolve('path','content', 'subfolder', 'test.txt');
console.log(testPath);

module.exports = testPath;

//fileSync_modules.js file code (located in 'fs' folder):

const fs = require('fs');

const testPath = require('../path/path_module')

const readFile = fs.readFileSync(testPath, 'utf8');
console.log(readFile);

When I run in VS. Code, the content of test.txt is visible. When I run in terminal, it gives a path error:

Error: ENOENT: no such file or directory, open 'C:\\Users\\home\\alvaro\\node\\fs\\path\\content\\subfolder\\test.txt'

As I'm running inside fs folder, it recognizes this folder as part of the path.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It looks like you're trying to make an path relative to the source file.

To do this, add __dirname to the start:

const testPath = path.resolve(__dirname, 'path','content', 'subfolder', 'test.txt');
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda