Ошибка enoent no such file or directory

I have a Node.js web application currently running on a server successfully. Now I’m trying to set up a local copy on my development server.

I currently have Node.js, NPM and MongoDB Installed just like what I have in production server. However, the error below occurs when I try to start the Node.js server.

What could be causing this issue?

cd ~/node/nodeapp
node app.js

Output:

fs.js:640
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/home/embah/node/nodeapp/config/c
onfig.json'
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at Object.fs.readFileSync (fs.js:508:33)
    at Object.<anonymous> (/home/embah/node/nodeapp/config/config.js:4:28)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/embah/node/glorby/app.js:13:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Peter Mortensen's user avatar

asked Apr 6, 2017 at 16:19

Emeka Mbah's user avatar

1

Your app is expecting to find a file at /home/embah/node/nodeapp/config/config.json but that file does not exist (which is what ENOENT means). So you either need to create the expected directory structure or else configure your application such that it looks in the correct directory for config.json.

answered Apr 6, 2017 at 16:23

Trott's user avatar

TrottTrott

66.6k24 gold badges173 silver badges212 bronze badges

0

After going through so many links and threads and getting frustrated over and over again, I went to the basics and boom! it helped. I simply did:

npm install

I don’t know, but it might help someone :)

answered Jun 16, 2018 at 21:15

olleh's user avatar

olleholleh

1,93518 silver badges21 bronze badges

5

Regarding:

92% additional asset processing scripts-webpack-plugin× 「wdm」: Error: ENOENT: no such file or directory, open….

If anyone faced to such an error, you should do followings:

  1. you should check if the file path is correct in the angular.json file.

    «scripts»: [
    «node_modules/jquery/dist/jquery.min.js»,
    «node_modules/bootstrap/dist/js/bootstrap.js»
    ],

  2. you should press Ctrl + C and rerun the project.

Peter Mortensen's user avatar

answered Jun 27, 2019 at 16:10

Odiljon Djamalov's user avatar

1

olleh’s answer worked, because npm install will create a node_modules directory in the current path where it is executed. So, while using the file server system module, the below declaration locate files from the top level directory of node_modules.

const fs = require('fs')

Peter Mortensen's user avatar

answered May 7, 2019 at 23:27

Aniruddha Pandey's user avatar

In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.

My directory stucture was like this:
projectfolder/
├── package.json
├── scriptFolder/
│ ├── myScript.js

And I was calling fs.createReadStream('users.csv') instead of the correct fs.createReadStream('scriptFolder/users.csv')

answered Jun 15, 2020 at 22:55

Chase Denecke's user avatar

0

If you have the same error while using Express.js in your project this worked for me:

In my project, when I ran an Express.js application, I noticed that the current working directory was the root directory of the project (while I was trying to read a file that was located in the script’s directory).
It could not run the file since process.cwd() !== __dirname.

You can check it out and console log process.cwd() in the script you are trying to read the JSON file with.

I just changed the path to:

const fs = require('fs');
fs.readFileSync(`${__dirname}\\FILENAME`);

Peter Mortensen's user avatar

answered Jan 29, 2022 at 20:20

Niv's user avatar

NivNiv

5231 gold badge8 silver badges19 bronze badges

I also had this issue, because I had another console window open that was running the application and I was attempting to rerun yarn start in another console window.

The first Yarn executing prevented the second from writing. So I just killed the first process and it worked.

Peter Mortensen's user avatar

answered May 15, 2018 at 8:24

Damian Green's user avatar

Damian GreenDamian Green

6,8952 gold badges31 silver badges43 bronze badges

1

I solved this error by simply creating a blank file at that location for which I got the error. If you are getting the error for a directory, you can try by also creating an empty directory.

Peter Mortensen's user avatar

answered Jun 13, 2020 at 17:58

sanghamitra Ravi Kant's user avatar

0

I was facing this issue with ng-package.json file, while creating a plugin. I found out I was providing the wrong path in angular.json. Fixed my file path, issue was resolved.

May be helpful for someone.

answered Mar 24, 2021 at 10:06

Analyst's user avatar

AnalystAnalyst

7616 silver badges15 bronze badges

In my case, the issue occurred after I switched from a Git branch to another, references to some old files remained in the scripts inside the «node_modules/.cache» directory.

Deleting the «node_modules», «build» directories and «package-lock.json» file and then issuing the «npm install» command has fixed the issue for me.

Peter Mortensen's user avatar

answered May 18, 2020 at 12:29

Hasnaa Ibraheem's user avatar

Hasnaa IbraheemHasnaa Ibraheem

1,1321 gold badge10 silver badges18 bronze badges

1

If there isn’t any layout folder, just use it like this in your routing:

app.get('/', (req, res) => {
    res.render('something', { layout: false });
})

Here change something with your folder name.

Peter Mortensen's user avatar

answered Jun 27, 2020 at 6:10

MD.FAHIM HOSSEN's user avatar

0

Make sure your angular.json file has the «style» and «scripts» array as below (for Angular 12 and above):

"styles": [
          "src/styles.css",
          "./node_modules/bootstrap/dist/css/bootstrap.css"
        ],
"scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ]

Once this is done, press Ctrl + C and then ng serve.

Peter Mortensen's user avatar

answered Jun 24, 2021 at 5:17

Ratnesh Rai's user avatar

I don’t know if anyone would see this, but I’ll say my answer.

First you need to be in the app directory that you created with the following command:

npx create-react-app [app-name]

Next run:

sudo npm install

to make it install all dependencies from

package.json

Then run:

sudo npm start

and make sure to run them with the sudo command, because sometimes it is absolutely necessary.

Peter Mortensen's user avatar

answered Dec 5, 2021 at 18:23

Javad's user avatar

JavadJavad

2132 silver badges9 bronze badges

1

I added the PM2_HOME environment variable on the system level and now it works all right.

Peter Mortensen's user avatar

answered Nov 2, 2020 at 15:27

kepy97's user avatar

kepy97kepy97

98810 silver badges12 bronze badges

1

If you’re coding with TypeScript, remember that the transpiled-JS folder is where JavaScript would be searching for your file and will definitely not be able to find your html-file; hence such error.

Therefore, you’d need to copy the file into the transpiledJS folder for it to be located.

Peter Mortensen's user avatar

answered Nov 15, 2021 at 13:30

Chukwunazaekpere's user avatar

Sometimes you see this issue in the following scenario.

Let’s assume that you have a folder structure like node-projects (folder) → my-blog (folder) → my-blog (folder where the actual project exists), but you are in the my-blog directly, and it is an immediate child of node-project. Try to run your command in that directory.

As the project is present in my-blog that is an immediate child of my-blog. So, in this case, it searches your config.json file in my-blog (which is an immediate child of node-projects) rather than finding the config.json file in my-blog that is an immediate child of my-blog.

Just transfer your directory by hitting the command cd my-blog in your terminal and that’s it. The problem is resolved!

Peter Mortensen's user avatar

answered Oct 18, 2022 at 21:27

HamzaKhalid273's user avatar

HamzaKhalid273HamzaKhalid273

3551 gold badge4 silver badges11 bronze badges

In my case

import { Object } from '../config/env';

gave me the error.

I solved it with change the address like this:

import { Object } from './../config/env';

answered Apr 24, 2019 at 13:40

msalihbindak's user avatar

Weirdly, in my project, I always get this error first time I add/remove a package, but then I run the same command again and it works on the second run.

answered Apr 25, 2022 at 14:59

Michal Kurz's user avatar

Michal KurzMichal Kurz

1,61213 silver badges42 bronze badges

My mistake was not adding / before the path. Correct path: /Users/mee/Documents/file_name.jpg

answered Oct 11, 2022 at 4:58

GorvGoyl's user avatar

GorvGoylGorvGoyl

42.9k29 gold badges229 silver badges227 bronze badges

It’s happened with me. I deleted some CSS files by mistake and then copied back. This error appeared at that time. So I restarted all my Docker images and other servers and then it went away.

Peter Mortensen's user avatar

answered Apr 3, 2019 at 11:35

Yasir Akbar's user avatar

Running

npm run scss
npm run start 

in that order in the terminal solved the issue for me.

Peter Mortensen's user avatar

answered Mar 11, 2020 at 11:44

Onat Korucu's user avatar

Onat KorucuOnat Korucu

1,00011 silver badges13 bronze badges

1

I tried something and got this error:

Error: ENOENT: no such file or directory, open ‘D:\Website\Nodemailer\Nodemailer-application\views\layouts\main.handlebars’

The fix I got was to literally construct the directory as it is seen. This means labeling the items exactly as shown. It is weird that I gave the computer what it wanted.

Peter Mortensen's user avatar

answered May 25, 2020 at 19:53

Blank456's user avatar

1

I had this error while uninstalling Bootstrap from the project, so I just deleted the script and style from file angular.json.

"styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
 "scripts": [
              "node_modules/jquery/dist/jquery.min.js"
          ]

Cleared this to

"styles"  : [    ],
"scripts" : [    ]

This solved my issue.

Peter Mortensen's user avatar

answered Jul 19, 2022 at 6:38

saurabh solanke's user avatar

I work with Visual Studio Code, Git and Nx and often have the problem that Visual Studio Code performs an auto staging.

In combination with Nx, it comes very often to problems. Simply unstaging the files in Visual Studio Code often helps.

answered Feb 25, 2022 at 12:36

TimJ0212's user avatar

TimJ0212TimJ0212

111 silver badge2 bronze badges

1

for me running

npm cache verify 

indicated that some file is corrupted and run the following command

sudo chown -R 501:20 "/Users/Mac/.npm"

did the trick. I assume the 2nd command will be your PC specific.

answered Jun 18 at 19:21

tk_tanz's user avatar

tk_tanztk_tanz

4023 silver badges7 bronze badges

Use __dirname:

const string = fs.readFileSync(__dirname + "/file.json", "utf8");

Tyler2P's user avatar

Tyler2P

2,32426 gold badges23 silver badges31 bronze badges

answered Jul 13 at 12:19

KISHORE K J's user avatar

KISHORE K JKISHORE K J

3064 silver badges4 bronze badges

I have a Node.js web application currently running on a server successfully. Now I’m trying to set up a local copy on my development server.

I currently have Node.js, NPM and MongoDB Installed just like what I have in production server. However, the error below occurs when I try to start the Node.js server.

What could be causing this issue?

cd ~/node/nodeapp
node app.js

Output:

fs.js:640
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/home/embah/node/nodeapp/config/c
onfig.json'
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at Object.fs.readFileSync (fs.js:508:33)
    at Object.<anonymous> (/home/embah/node/nodeapp/config/config.js:4:28)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/embah/node/glorby/app.js:13:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Peter Mortensen's user avatar

asked Apr 6, 2017 at 16:19

Emeka Mbah's user avatar

1

Your app is expecting to find a file at /home/embah/node/nodeapp/config/config.json but that file does not exist (which is what ENOENT means). So you either need to create the expected directory structure or else configure your application such that it looks in the correct directory for config.json.

answered Apr 6, 2017 at 16:23

Trott's user avatar

TrottTrott

66.6k24 gold badges173 silver badges212 bronze badges

0

After going through so many links and threads and getting frustrated over and over again, I went to the basics and boom! it helped. I simply did:

npm install

I don’t know, but it might help someone :)

answered Jun 16, 2018 at 21:15

olleh's user avatar

olleholleh

1,93518 silver badges21 bronze badges

5

Regarding:

92% additional asset processing scripts-webpack-plugin× 「wdm」: Error: ENOENT: no such file or directory, open….

If anyone faced to such an error, you should do followings:

  1. you should check if the file path is correct in the angular.json file.

    «scripts»: [
    «node_modules/jquery/dist/jquery.min.js»,
    «node_modules/bootstrap/dist/js/bootstrap.js»
    ],

  2. you should press Ctrl + C and rerun the project.

Peter Mortensen's user avatar

answered Jun 27, 2019 at 16:10

Odiljon Djamalov's user avatar

1

olleh’s answer worked, because npm install will create a node_modules directory in the current path where it is executed. So, while using the file server system module, the below declaration locate files from the top level directory of node_modules.

const fs = require('fs')

Peter Mortensen's user avatar

answered May 7, 2019 at 23:27

Aniruddha Pandey's user avatar

In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.

My directory stucture was like this:
projectfolder/
├── package.json
├── scriptFolder/
│ ├── myScript.js

And I was calling fs.createReadStream('users.csv') instead of the correct fs.createReadStream('scriptFolder/users.csv')

answered Jun 15, 2020 at 22:55

Chase Denecke's user avatar

0

If you have the same error while using Express.js in your project this worked for me:

In my project, when I ran an Express.js application, I noticed that the current working directory was the root directory of the project (while I was trying to read a file that was located in the script’s directory).
It could not run the file since process.cwd() !== __dirname.

You can check it out and console log process.cwd() in the script you are trying to read the JSON file with.

I just changed the path to:

const fs = require('fs');
fs.readFileSync(`${__dirname}\\FILENAME`);

Peter Mortensen's user avatar

answered Jan 29, 2022 at 20:20

Niv's user avatar

NivNiv

5231 gold badge8 silver badges19 bronze badges

I also had this issue, because I had another console window open that was running the application and I was attempting to rerun yarn start in another console window.

The first Yarn executing prevented the second from writing. So I just killed the first process and it worked.

Peter Mortensen's user avatar

answered May 15, 2018 at 8:24

Damian Green's user avatar

Damian GreenDamian Green

6,8952 gold badges31 silver badges43 bronze badges

1

I solved this error by simply creating a blank file at that location for which I got the error. If you are getting the error for a directory, you can try by also creating an empty directory.

Peter Mortensen's user avatar

answered Jun 13, 2020 at 17:58

sanghamitra Ravi Kant's user avatar

0

I was facing this issue with ng-package.json file, while creating a plugin. I found out I was providing the wrong path in angular.json. Fixed my file path, issue was resolved.

May be helpful for someone.

answered Mar 24, 2021 at 10:06

Analyst's user avatar

AnalystAnalyst

7616 silver badges15 bronze badges

In my case, the issue occurred after I switched from a Git branch to another, references to some old files remained in the scripts inside the «node_modules/.cache» directory.

Deleting the «node_modules», «build» directories and «package-lock.json» file and then issuing the «npm install» command has fixed the issue for me.

Peter Mortensen's user avatar

answered May 18, 2020 at 12:29

Hasnaa Ibraheem's user avatar

Hasnaa IbraheemHasnaa Ibraheem

1,1321 gold badge10 silver badges18 bronze badges

1

If there isn’t any layout folder, just use it like this in your routing:

app.get('/', (req, res) => {
    res.render('something', { layout: false });
})

Here change something with your folder name.

Peter Mortensen's user avatar

answered Jun 27, 2020 at 6:10

MD.FAHIM HOSSEN's user avatar

0

Make sure your angular.json file has the «style» and «scripts» array as below (for Angular 12 and above):

"styles": [
          "src/styles.css",
          "./node_modules/bootstrap/dist/css/bootstrap.css"
        ],
"scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ]

Once this is done, press Ctrl + C and then ng serve.

Peter Mortensen's user avatar

answered Jun 24, 2021 at 5:17

Ratnesh Rai's user avatar

I don’t know if anyone would see this, but I’ll say my answer.

First you need to be in the app directory that you created with the following command:

npx create-react-app [app-name]

Next run:

sudo npm install

to make it install all dependencies from

package.json

Then run:

sudo npm start

and make sure to run them with the sudo command, because sometimes it is absolutely necessary.

Peter Mortensen's user avatar

answered Dec 5, 2021 at 18:23

Javad's user avatar

JavadJavad

2132 silver badges9 bronze badges

1

I added the PM2_HOME environment variable on the system level and now it works all right.

Peter Mortensen's user avatar

answered Nov 2, 2020 at 15:27

kepy97's user avatar

kepy97kepy97

98810 silver badges12 bronze badges

1

If you’re coding with TypeScript, remember that the transpiled-JS folder is where JavaScript would be searching for your file and will definitely not be able to find your html-file; hence such error.

Therefore, you’d need to copy the file into the transpiledJS folder for it to be located.

Peter Mortensen's user avatar

answered Nov 15, 2021 at 13:30

Chukwunazaekpere's user avatar

Sometimes you see this issue in the following scenario.

Let’s assume that you have a folder structure like node-projects (folder) → my-blog (folder) → my-blog (folder where the actual project exists), but you are in the my-blog directly, and it is an immediate child of node-project. Try to run your command in that directory.

As the project is present in my-blog that is an immediate child of my-blog. So, in this case, it searches your config.json file in my-blog (which is an immediate child of node-projects) rather than finding the config.json file in my-blog that is an immediate child of my-blog.

Just transfer your directory by hitting the command cd my-blog in your terminal and that’s it. The problem is resolved!

Peter Mortensen's user avatar

answered Oct 18, 2022 at 21:27

HamzaKhalid273's user avatar

HamzaKhalid273HamzaKhalid273

3551 gold badge4 silver badges11 bronze badges

In my case

import { Object } from '../config/env';

gave me the error.

I solved it with change the address like this:

import { Object } from './../config/env';

answered Apr 24, 2019 at 13:40

msalihbindak's user avatar

Weirdly, in my project, I always get this error first time I add/remove a package, but then I run the same command again and it works on the second run.

answered Apr 25, 2022 at 14:59

Michal Kurz's user avatar

Michal KurzMichal Kurz

1,61213 silver badges42 bronze badges

My mistake was not adding / before the path. Correct path: /Users/mee/Documents/file_name.jpg

answered Oct 11, 2022 at 4:58

GorvGoyl's user avatar

GorvGoylGorvGoyl

42.9k29 gold badges229 silver badges227 bronze badges

It’s happened with me. I deleted some CSS files by mistake and then copied back. This error appeared at that time. So I restarted all my Docker images and other servers and then it went away.

Peter Mortensen's user avatar

answered Apr 3, 2019 at 11:35

Yasir Akbar's user avatar

Running

npm run scss
npm run start 

in that order in the terminal solved the issue for me.

Peter Mortensen's user avatar

answered Mar 11, 2020 at 11:44

Onat Korucu's user avatar

Onat KorucuOnat Korucu

1,00011 silver badges13 bronze badges

1

I tried something and got this error:

Error: ENOENT: no such file or directory, open ‘D:\Website\Nodemailer\Nodemailer-application\views\layouts\main.handlebars’

The fix I got was to literally construct the directory as it is seen. This means labeling the items exactly as shown. It is weird that I gave the computer what it wanted.

Peter Mortensen's user avatar

answered May 25, 2020 at 19:53

Blank456's user avatar

1

I had this error while uninstalling Bootstrap from the project, so I just deleted the script and style from file angular.json.

"styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
 "scripts": [
              "node_modules/jquery/dist/jquery.min.js"
          ]

Cleared this to

"styles"  : [    ],
"scripts" : [    ]

This solved my issue.

Peter Mortensen's user avatar

answered Jul 19, 2022 at 6:38

saurabh solanke's user avatar

I work with Visual Studio Code, Git and Nx and often have the problem that Visual Studio Code performs an auto staging.

In combination with Nx, it comes very often to problems. Simply unstaging the files in Visual Studio Code often helps.

answered Feb 25, 2022 at 12:36

TimJ0212's user avatar

TimJ0212TimJ0212

111 silver badge2 bronze badges

1

for me running

npm cache verify 

indicated that some file is corrupted and run the following command

sudo chown -R 501:20 "/Users/Mac/.npm"

did the trick. I assume the 2nd command will be your PC specific.

answered Jun 18 at 19:21

tk_tanz's user avatar

tk_tanztk_tanz

4023 silver badges7 bronze badges

Use __dirname:

const string = fs.readFileSync(__dirname + "/file.json", "utf8");

Tyler2P's user avatar

Tyler2P

2,32426 gold badges23 silver badges31 bronze badges

answered Jul 13 at 12:19

KISHORE K J's user avatar

KISHORE K JKISHORE K J

3064 silver badges4 bronze badges

The «Error: ENOENT: no such file or directory» error in Node.js occurs when the file or directory specified in a file system operation does not exist. This error can occur when trying to read, write, or execute a file or directory, or when trying to access a required module or resource. In order to resolve this issue, there are several methods that can be tried.

Method 1: Check the file path

To resolve the «Node.Js: Error: ENOENT: no such file or directory» error, you can check the file path. Here are the steps to do it:

  1. First, make sure that the file path is correct. You can use the path module to join the path segments together.
const path = require('path');
const filePath = path.join(__dirname, 'file.txt');
  1. Then, check if the file exists using the fs module’s existsSync() method.
const fs = require('fs');
if (fs.existsSync(filePath)) {
  // file exists
} else {
  // file does not exist
}
  1. If the file exists, you can read it using the fs module’s readFileSync() method.
const fileContent = fs.readFileSync(filePath, 'utf-8');
console.log(fileContent);

Here’s the complete example code:

const path = require('path');
const fs = require('fs');

const filePath = path.join(__dirname, 'file.txt');

if (fs.existsSync(filePath)) {
  const fileContent = fs.readFileSync(filePath, 'utf-8');
  console.log(fileContent);
} else {
  console.log('File does not exist');
}

This code will check if the file exists and read its content if it does. Otherwise, it will log a message saying that the file does not exist.

Method 2: Create the missing directory or file

To resolve the «Nodejs: Error: ENOENT: no such file or directory» error in Node.js, you can create the missing directory or file using the fs module. Here’s how to do it in steps:

  1. Import the fs module:
const fs = require('fs');
  1. Use the fs.existsSync() method to check if the directory or file exists:
if (!fs.existsSync('/path/to/directory')) {
  // Create the directory
  fs.mkdirSync('/path/to/directory', { recursive: true });
}
  1. If the directory or file doesn’t exist, use the fs.mkdirSync() method to create it:
if (!fs.existsSync('/path/to/file')) {
  // Create the file
  fs.writeFileSync('/path/to/file', 'File content');
}

Here’s the complete code:

const fs = require('fs');

if (!fs.existsSync('/path/to/directory')) {
  // Create the directory
  fs.mkdirSync('/path/to/directory', { recursive: true });
}

if (!fs.existsSync('/path/to/file')) {
  // Create the file
  fs.writeFileSync('/path/to/file', 'File content');
}

This code will create the missing directory or file if it doesn’t exist, and prevent the «Nodejs: Error: ENOENT: no such file or directory» error from occurring.

Method 3: Verify that required modules are installed

To resolve the «Node.Js: Error: ENOENT: no such file or directory» error, one of the methods is to verify that required modules are installed. Here are the steps to do it:

  1. Open the terminal or command prompt and navigate to the project directory.

  2. Check if the required module is listed in the package.json file under the dependencies section. If not, add it manually or install it using the following command:

    npm install <module-name> --save
  3. If the module is installed, check if it is imported in the file where the error occurs using the require function. For example:

    const fs = require('fs');
  4. If the module is imported, check if the file path is correct. For example:

    const filePath = './data/file.txt';
    fs.readFile(filePath, (err, data) => {
      if (err) throw err;
      console.log(data);
    });
  5. If the file path is correct, check if the file actually exists in the specified location. For example:

    const filePath = './data/file.txt';
    if (fs.existsSync(filePath)) {
      fs.readFile(filePath, (err, data) => {
        if (err) throw err;
        console.log(data);
      });
    } else {
      console.log('File not found');
    }

By following these steps, you can verify that the required modules are installed and the file path is correct, which should resolve the «Node.Js: Error: ENOENT: no such file or directory» error.

Method 4: Check for typos in file/directory names

If you encounter the Nodejs: Error: ENOENT: no such file or directory error in Node.js, one of the possible causes is that the file or directory path you’re trying to access doesn’t exist. One way to resolve this issue is to check for typos in the file/directory names.

Here’s an example code that demonstrates how to check for typos in file/directory names:

const fs = require('fs');

const filePath = '/path/to/missing/file.txt';

fs.access(filePath, fs.constants.F_OK, (err) => {
  if (err) {
    console.error(`File "${filePath}" does not exist or is not readable.`);
    console.error(`Please check for typos in the file path and try again.`);
    return;
  }

  // File exists, do something with it
  console.log(`Reading file "${filePath}"...`);
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file "${filePath}":`, err);
      return;
    }
    console.log(`File content: "${data}"`);
  });
});

In this example, we use the fs.access() method to check if the file at the given path exists and is readable. If the file doesn’t exist or is not readable, we log an error message that suggests checking for typos in the file path.

If the file exists, we can proceed with reading its contents using the fs.readFile() method.

By checking for typos in file/directory names, you can avoid the Nodejs: Error: ENOENT: no such file or directory error and ensure that your Node.js application can access the required files and directories.

Method 5: Ensure the file or directory has the correct permissions

To ensure that the file or directory has the correct permissions, you can use the fs.access() method in Node.js. This method checks if the file or directory exists and if the current user has the necessary permissions to access it.

Here is an example code snippet that demonstrates how to use fs.access() to resolve the ENOENT error:

const fs = require('fs');

const filePath = '/path/to/file.txt';

fs.access(filePath, fs.constants.F_OK | fs.constants.R_OK, (err) => {
  if (err) {
    console.error(`Error accessing file: ${err}`);
    return;
  }

  // File exists and is readable
  // Your code logic here
});

In this example, fs.access() takes three arguments: the file path, a bit mask of flags indicating the type of access to check for (fs.constants.F_OK for existence and fs.constants.R_OK for read permission), and a callback function that is called with an error if the access check fails.

If the file exists and is readable, the callback function is called without an error and you can proceed with your code logic.

Note that fs.access() only checks for the existence and permissions of the file or directory at the time of the call. It does not guarantee that the file or directory will remain accessible in the future.

Web development has come a long way now. Instead of using simple HTML/CSS, Javascript and PHP to build websites, developers now can choose from plenty of web development frameworks and server tools that make the job easier. 

In this article, we’re looking at the “enoent: no such file or directory” error when running Node.js web servers, its causes and what you can do to fix the problem.


What causes this error?

As the error message describes, the problem is caused by a missing configuration file or other dependencies required for your website or web app to run properly. 

Other possible causes include the following:

  • Incorrect file paths for web server configuration files. 
  • NPM configuration folders aren’t made.

Also read: Fix: An unexpected error is keeping you from copying the file


How to fix this?

Here are five fixes you can try out. 

Restart your PC

A quick and simple fix for the problem is to restart your PC. This ensures that any missing processes start up correctly alongside your operating system and that everything is in order before running your project.


Create an NPM directory

One of the main reasons you’d run into this error is that NPM doesn’t have a configuration directory to keep track of your project’s dependencies. 

The simplest way to fix this is to run the npm install command. If that doesn’t work, you can also try running npm update. Running both commands back to back can also sometimes fix the problem. 

Also read: Docs.google.com refused to connect: 6 Fixes


Check your configuration files

Take a good look at the directory that the error message shows. The file at the end is the missing dependency that’s causing this problem. While it can be any of the dependencies in your project, this is often a missing configuration file. 

To resolve the error, you can manually create the mentioned file path with the specified file at the end. Do keep in mind that while it might fix the problem we’re dealing with in this article, it can give you additional errors, as the resulting file will be empty. 

Make sure your configuration files are in the right place and using the right Node version.

You can then work your way around the new error, if any, by installing any required packages that might be missing from your project. 


Fix the file path

As an extension to the last solution, you can also try and manually fix the file path that the error has reported missing. The specific way to do this varies from framework to framework, so you’ll have to look up the documentation of your specific framework in use to check how to modify file paths.

If you’re sure that the configuration file or dependencies exist, you can manually point your web server to the right file. 


Reinitialise your project

You also might have to reinitialise your project to freshen up all the dependencies you’re using. This can be done by deleting the node_modules folder and the package-lock.json file. Just open a terminal, head over to your project’s root folder and run the following commands one at a time.

rm -rf node_modules package-lock.json
npm install

Error: Cannot find module express: 3 Fixes

If you get an error saying you don’t have appropriate permissions to carry out these tasks, prefix sudo to both commands. 

Also read: Fix: Unknown error: soap-error: encoding: object has no uirequestid property

Why are you getting the enoent errorThe “enoent” can appear because of some missing files or usage of the relative path that can be solved by creating an expected directory structure or using an absolute path, respectively. There are also many other reasons for getting this error. This article contains all those causes and solutions with developers’ tips to solve the error quickly. So keep reading this article till the end to learn what is necessary to fix this error.

Contents

  • What Are the Causes of Getting “Enoent” Error Messages?
    • – Starting the Node Server
    • – Using a File Path Starting at the Directory Where the Script Was Executing
    • – Having Another Console Windows
    • – Having No Layout Folder
    • – Sudo Command
    • – Wrong Path in Angular.json
    • – Switching Git Branch
    • – The angular.json File Doesn’t Have the “Styles” and “Scripts” Array.
    • – Typescript
    • – Mismatched Node Version
    • – Express.JS
    • – Getting Script-webpack-Plugin Error Message Along With Enoent Error
    • – Delete Some CSS Files
    • – Using a Relative Path
    • – Node Script
  • How To Solve the “Enoent” Error
    • – Starting the Node Server
    • – Using a File Path Starting at the Directory Where the Script Was Executing
    • – Having Another Console Windows
    • – Having No Layout Folder
    • – Sudo Command
    • – Switching Git Branch
    • – The angular.json File Doesn’t Have the “Styles” and “Scripts” Array
    • – Typescript
    • – Express.js
    • – Getting Script-webpack-Plugin Error Message Along With Enoent Error
    • – Delete Some CSS Files
    • – Using a Relative Path
    • – Node Script
  • FAQs
    • – What Is the Enoent?
    • – What Does Enoent: No Such File or Directory Mean?
  • Conclusion

What Are the Causes of Getting “Enoent” Error Messages?

To solve the “enoent” error message, we first need to understand why this error appears. Let’s find out some of the common causes of this error.

– Starting the Node Server

This error can appear while starting the node server. This can happen because of the no existence of some important files at the expected location.

– Using a File Path Starting at the Directory Where the Script Was Executing

You can get this error if you use a file path that starts at the directory where scripts are executing but not at the project’s root.

– Having Another Console Windows

You can face this error if you have another conarele windows open that is running the app, and you try to re-run yarn to start in another console window.

– Having No Layout Folder

Having no layout folder can also be one of the causes here.

– Sudo Command

Anything wrong is the Sudo command or not running the sudo command will not allow you to write to /private/var/folders on mac, and this error appears.

– Wrong Path in Angular.json

A prevalent cause of this error is providing the wrong file path in angular.json, where you can fix the path to remove the error.

– Switching Git Branch

This error can appear if you switch from one git branch to another. The latter happened because some old files remained in the scripts inside the “node_module/.cache” directory.

– The angular.json File Doesn’t Have the “Styles” and “Scripts” Array.

If you are working in Angular 12 or above, and your angular.json file doesn’t have the “styles” and “scripts” arrays, you can also get this error in that condition.

– Typescript

If you are working on typescript, the JS will find the HTML file in the transpiled-JS folder. And if your HTML file is not present there, you will see the error.

– Mismatched Node Version

If you have installed the mismatch node version, you would probably get the error. You just need to install the correct node version via nvm to eliminate this error.

– Express.JS

If you are working with express.js and getting the same error, this could be because the current working directory might be the project’s root directory. You might be trying to read the file located in the script’s directory, and in this case, you might not run the file as a process.cwd() !==__dirname. This out and do the console log process.cwd() in the script you attempt to read JSON file.

– Getting Script-webpack-Plugin Error Message Along With Enoent Error

In some cases, you might get the script-webpack-plugin error and enoent value error. That could be because of the wrong path. You can get both of these errors on node.js or angular.

– Delete Some CSS Files

If you are working in CSS, you can face this error, have mistakenly deleted some critical CSS files and then copied them back.

– Using a Relative Path

If you are working on an API and some request, you might be using a relative path if you get this error with a message that it can’t read a path that doesn’t exist.

– Node Script

You can get this error while working with Node script and trying to transfer the files in use. Though most of the time, the error appears because of the files and folders that do not exist, you might experience that when you are close the chrome, the error gets removed.

It is happening because there is a symbolic link named RunningChromeVersion whose target doesn’t exist. The Node script doesn’t give any special treatment to links, so the default action is to follow the link when you try to open them. Like’s target doesn’t exist because it is not supposed to point to a file. It’s a dummy link with unrelated information like the version number stored in the “target” field where a file goes typically.

We discovered many causes of this error; let’s find out the solutions

– Starting the Node Server

If you are getting this error while starting the enoent nodejs server, there might be a need for some essential files not present in the expected location. If this is the case, you would see that it complained about missing a file. That is why, you need to create the expected directory structure. You can also configure the application you are working on to look in the correct directory.

If it is still not solved, go to the basics, and install enoent npm. If the problem is not solved yet, go for “npm update,” and then try “npm install.”

Using the “npm install,” a “node_module” directory in the current path will be created, the location where it is executed. When you use the “file server system module,” the below declaration will locate files from the “node modules,” a top-level directory.

const fs = require(‘fs’)

– Using a File Path Starting at the Directory Where the Script Was Executing

The simple and quick solution, in this case, is to use the below path while calling.

fs.createReadStream(‘scriptFolder/users.csv’)

– Having Another Console Windows

If you are having another console open and facing this issue, what happens is that as the first yarn executes, it prevents the second yarn from writing. As a solution, you can simply kill the first process, and you see it will work.

– Having No Layout Folder

If you don’t have a layout folder for your routine, you can use the enoent code below.

app.get(‘/’, (req,res)=>{
res.render(‘FolderName’, {layout: false});
})

Just change “FolderName” with your folder name, and your problem will be fixed.

– Sudo Command

To solve this issue, you need to follow some steps.

In the first step, you need to be in the app directory created by the following command.

npx create-react-app [app-name]

Then run the following

sudo npm install

To make it install all dependencies from the following

package.json

And then run the following

sudo npm start

Here you need to ensure that you run them with Sudo commands, which sometimes becomes indispensable.

– Switching Git Branch

If the issue is created because of switching between git branches, then you should delete “node_modules,” “build” directories, and “package-lock.json” files, and then you can issue the “npm install” command to fix the issue.

– The angular.json File Doesn’t Have the “Styles” and “Scripts” Array

If you are facing this issue because your angular.json file doesn’t have the “styles” and “scripts” arrays, you can add them to fix the problem. Those arrays are as follows:

“Styles”: [
“src/styles.css,”
“./node_modules/bootstrap/dist/css/bootstrap.css”
],
“Scripts”: [
“node_modules/jquerry/dist/jquerry.min.js”,
“node_modules/bootstrap/dist/js/bootstrap.js”
]

In the end, press CTRL+C and then ng serve.

– Typescript

If you are getting the error because the JS is not finding the HTML file in the transpiled-JS folder, you need to copy the file into the transpiled-JS folder where it should be located so that the JS can see the HTML file.

– Express.js

If you are working with express.js and getting this error, you should change the path to the following:

Const fs = require(‘fs’);
fs.readFileSync(‘${__dirname}\FILENAME’);

– Getting Script-webpack-Plugin Error Message Along With Enoent Error

If you are getting the script-webpack-plugin error message along with an enoent error, the cause for this error could be the wrong path. You first need to make sure the file path is correct in the angular.JSON file.

“Scripts”: [
“node_modules/jquery/dist/jquery/min.js”,
“node_modules/bootstrap/dist/js/bootstrap.js”
],

And then copy this and rerun the project.

You should also check the file path relative to the angular.json configuration file. You might have to add the root folder name as well.

– Delete Some CSS Files

If you are getting this error because of deleting some CSS files first and then copying them, you should restart your docker and other servers to remove the error.

– Using a Relative Path

If you are choosing a relative path, in this case, you are going to get this error. So to avoid the error, you should select the absolute path. And if your problem is still not solved, you can check the body—path value.

– Node Script

As a solution, you can use the Node equivalent of the lstat() to make sure whether the path is a symlink avoid transferring it in the same way. If you want to read the ‘target’ field, you can use readlink(). You should skip the symlinks while recursive file researching because it is possible that if you follow the symlink, you might get into the infinite loop.

FAQs

– What Is the Enoent?

The enoent meaning error no entry. This is used for more than files or dictionaries.

– What Does Enoent: No Such File or Directory Mean?

No such files or directory means that the library is currently needed or the executable binary doesn’t exist.

Conclusion

Let’s review what we learned today:

  • Some causes can lead you to this error, including starting the node server or using a file path starting at the directory where the script was executed.
  • You must have all the essential files at the expected location; otherwise, you must create the expected directory structure to avoid this error.
  • Don’t use the relative path rather than the absolute path.

How to fix the error no entry errorThis article covered all the causes that can lead you to face the “enoent” error and their solutions. It’s time to meet this error with the help of this article and remove all the hurdles that stop you from coding.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Ошибка engine oil pressure too low пежо 207
  • Ошибка engine oil pressure too low citroen c5
  • Ошибка engine oil pressure fault stop
  • Ошибка engine management system faulty ситроен с4
  • Ошибка engine management system faulty citroen c5