Error enoent no such file or directory stat c index html

I'm having some trouble debugging this issue. Pretty much I have a Node.js that serves a React application and also acts as a REST API. The server runs on port 8080 by default. import express, {Re...

I’m having some trouble debugging this issue. Pretty much I have a Node.js that serves a React application and also acts as a REST API. The server runs on port 8080 by default.

import express, {Request, Response} from 'express';
import path from 'path';
import helmet from 'helmet';
import morgan from 'morgan';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import {ENVIRONMENT, PORT} from '../util/secrets';
// Import API Routes
import * as home from './controllers/home';

// Create express server
const app = express();

// Add middleware
app.use(helmet());
app.use(morgan('combined'));

// Define API routes
app.get('/api/', home.get);

// Configure environment settings
if (ENVIRONMENT === 'development') {
    // ...
} else {
    // Configure Static Files (Production)
    app.use(express.static("./"));

    // Serve React Static Files (Production)
    app.get('*', (req: Request, res: Response) => {
        res.sendFile(path.resolve(__dirname, "/index.html"));
    });
}

// Start server
app.listen(PORT, () => {
    console.log(`Express started on http://localhost:${PORT}/ in ${ENVIRONMENT} mode.`);
});

export default app;
module.exports = app;

Basically I go to localhost:8080 and my app renders just fine. However when I go to localhost:8080/login I get the following response from the server:

Error: ENOENT: no such file or directory, stat '/index.html'
/index.html

Here are the morgan logs:

::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET /app.bundle.js HTTP/1.1" 304 - "http://localhost:8080/" "M
ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
"
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:20 +0000] "GET /login HTTP/1.1" 404 195 "-" "Mozilla/5.0 (Windows NT 10.0
; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"

Why does it render my app on localhost:8080 but not localhost:8080/login

Dist Folder:

dist
  img
  app.bundle.js
  index.html
  server.bundle.js

#html #node.js #express #heroku

Вопрос:

Я развернул index.html страницу с помощью Node.JS in Heroku . Это файловая структура, которой я следую в Heroku

 -- Index.js
 -- public
     -- css
          -- index.css
     -- JS
          -- index.js
     -- index.html
     -- home.html
 -- procfile
 -- package.json
 

В серверном скрипте index.js

 //express
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000
const path = require('path')


app.get('/', function (req, res) {
    console.log("Current directory:", __dirname);
    console.log("filename: ", __filename);
  
    //serve the html page
    res.sendFile(path.join(__dirname, '/public/index.html'));
  });

app.listen(PORT, () => {
    console.log(`Listening on ${PORT}`);
  }); 
 

После развертывания кода и запуска server.js файл , я получаю ошибку ниже

 Error: ENOENT: no such file or directory, stat '/app/public/index.html'
 

Я не понимаю, почему возникает эта ошибка. У меня есть index.html файл в public папке.

Поэтому, чтобы понять путь к героку, я добавил следующие строки в server.js файл

 console.log("Current directory:", __dirname); // return the path
console.log("filename: ", __filename); // return the index.js file path
 

и соответствующий вывод выглядит следующим образом:

 Current directory: /app
filename:  /app/index.js
 

Теперь /app это основной каталог приложения. Так почему res.sendFile(path.join(__dirname, '/public/index.html')); же тогда возвращается то error no such file or directory, stat '/app/public/index.html' ?

Также я пробовал express.static метод в server.js подобных

 app.use(express.static(__dirname   '/public'));

app.get('/', function (req, res) {
   res.sendFile('index.html');
 });
 

затем я получил новую ошибку

 TypeError: path must be absolute or specify root to res.sendFile
 

После этого я попробовал еще один метод

 app.use(express.static(__dirname   '/public'));

app.get('/', function (req, res) {
    res.sendFile('public/index.html', { root: __dirname });
});
 

Затем я получил ту же ошибку Error: ENOENT: no such file or directory, stat '/app/public/index.html'

Есть какие-нибудь предложения? Как получить доступ index.html и home.html что я здесь делаю не так ?

Ответ №1:

Попробуйте использовать:

 res.sendFile(path.join(__dirname, 'public', 'index.html'));
 

Комментарии:

1. получение ошибки sam Error: ENOENT: no such file or directory, stat '/app/public/index.html'

Comments

@hackhat

Description

I’m getting a lot of similar errors to this:

 success Building production JavaScript and CSS bundles — 8.258 s
 ⠐ Building static HTML for pageserror ../public/29/path---internal-80-aeac-04-012-a-4-feb-9-d-99-d- 
   6053-a-12-be-5-a-r-006-91-c-794-olfyUiQvtLIAh9ozYkUiFQEB1M
 { Error: ENOENT: no such file or directory, open' X:xxxxxxpublicstaticd29path---internal-80-aeac-04-012-a-4-feb-9-d-99-d-6053-a-12-be-5-a-r-006-91-c-794-olfyUiQvtLIAh9ozYkUiFQEB1M.json'

and then hangs with » Building static HTML for pages» for long time.

Steps to reproduce

Don’t know… Just deleted the public folder and build it.

Environment

Run gatsby info --clipboard in your project directory and paste the output here. Not working? You may need to update your global gatsby-cli — npm install -g gatsby-cli

System:
OS: Windows 10
CPU: x64 Intel(R) Core(TM) i7-5600U CPU @ 2.60GHz
Binaries:
Yarn: 1.9.4 — C:Program Files (x86)Yarnbinyarn.CMD
npm: 5.5.1 — C:Program Filesnodejsnpm.CMD
Browsers:
Edge: 42.17134.1.0
npmPackages:
gatsby: ^2.0.67 => 2.0.67
gatsby-image: ^2.0.25 => 2.0.25
gatsby-plugin-catch-links: ^2.0.9 => 2.0.9
gatsby-plugin-emotion: ^3.0.1 => 3.0.1
gatsby-plugin-google-analytics: ^2.0.8 => 2.0.8
gatsby-plugin-manifest: ^2.0.12 => 2.0.12
gatsby-plugin-offline: ^2.0.19 => 2.0.19
gatsby-plugin-react-helmet: ^3.0.0 => 3.0.0
gatsby-plugin-sharp: ^2.0.15 => 2.0.15
gatsby-plugin-sitemap: ^2.0.3 => 2.0.3
gatsby-plugin-typescript: ^2.0.3 => 2.0.3
gatsby-plugin-typography: ^2.2.2 => 2.2.2
gatsby-remark-component: ^1.1.3 => 1.1.3
gatsby-remark-images: ^3.0.1 => 3.0.1
gatsby-source-filesystem: ^2.0.12 => 2.0.12
gatsby-transformer-remark: ^2.1.15 => 2.1.15
gatsby-transformer-sharp: ^2.1.9 => 2.1.9

@hackhat

Ok, so I had this issue: #10458 I run gatsby develop a few times and now it works. Then I build and it works.. what is going on? I need to run gatsby develop before building?

@hackhat

I deleted my public folder and build again, same error again.

I deleted cache folder and build and now it worked.

blopa, moelfassi, sketchthat, arnaudambro, afnizarnur, pranayaryal, Hitmasu, yberg, Vacilando, kentrh, and 66 more reacted with thumbs up emoji
whyboris, redconfetti, bmwant, miketheodorou, mo-sharif, NomanGul, Tapha, nvana, Haru0101, jaraujocds, and caseyocampo reacted with laugh emoji
lfurzewaddock, amazingrando, emiljohansson, edsu, ConstantinChirila, herecydev, barbalex, timmoti, marcelkooi, clarmso, and 33 more reacted with hooray emoji
adonig, nvana, and hangingPandaReact reacted with confused emoji
wcparker829, blopa, harsilspatel, alexcaulfield, whyboris, webberwang, LemUhuru, wolfcito, bronsonavila, MonikaPatelIT, and 12 more reacted with heart emoji
MonikaPatelIT, whyboris, redconfetti, bmwant, miketheodorou, mo-sharif, NomanGul, Tapha, kidager, Khromchenko, and 4 more reacted with rocket emoji
whyboris, Tapha, and Haru0101 reacted with eyes emoji

@DSchau

Hello!

Sorry about the issues! Could you provide a reproduction or something we could take a look at? Thanks!

@hackhat

I can’t… is just in my project and I don’t have a clue about what is affecting this. It’s incredibly flaky.

@DSchau

If it’s something that happens every X times, e.g. every ~5 times or something, and you can reproduce it occasionally that’s still more to go on that we have now.

It’s pretty challenging to know how to begin debugging this. At first glance, it could be some type of Windows pathing issue, but that’s a shot in the dark at this point.

Thanks!

@hackhat

If I run gatsby start and then run gatsby build it fails. If I delete the cache folder and run gatsby build it works.

FredericMartinez, danielpuehringer, jeltehomminga, kashiraja, whalesingswee, mlafuentecr, ipy, Mohcka, GFargo, luxjoshyua, and 7 more reacted with thumbs up emoji
kashiraja, whalesingswee, and rmoylan reacted with hooray emoji

@DSchau

That’s enough for us to go on! Is it possible to share the repository (or create a minified example without any private info) so we could take a look ourselves?

@hackhat

I can’t right now, is pretty big and entangled… What can we do?

@pieh

We do output query results to public directory directly, but we keep track of them in .cache — so if you delete public without deleting .cache — cache won’t know that query results are no longer there and that’s why we it complains about missing file that cache expects to be there

@hackhat

@pieh Looks like it’s correct. So probably we should do something to avoid this scenario. Maybe put an error that in order to build without public folder you need to delete the .cache folder as well.

But I found it strange for the .cache to look into the public folder… but anyway, that’s something else.

@pieh

But I found it strange for the .cache to look into the public folder… but anyway, that’s something else.

So this is kind of to eliminate some of the «unnecessary» work — like if we output query results to .cache we would need to copy them later on to public anyway. But for sure it comes with issues like that. We definitely could/should check if query results are available and rerun queries if they are not

@jonniebigodes

@hackhat this a bit of a edge case, normally people don’t even touch these folders, or if they do they delete both of them, either by using a script, or using an auxiliary package to handle that situation.
And controlling the scenario you mentioned could be a bit tricky, as both folders are automatically generated, if not present they are generated and their content filled by gatsby and if they are gatsby goes about it’s business, starts incrementally making the checks needed and updating the contents incrementally. And if everything is working properly you get an ok, or like it happened to you it throws an error.
I believe that this should be a case to be handled by the actual developer, not the tool itself. Before issuing production build and/or issuing the development command you should do some «house cleaning» (pardon the bad pun) beforehand and always getting the correct/actual data/contents you have. And i might be completely off on this, and feel free to correct me, but it’s a defensive strategy i adopted that’s been working for me since i’ve discovered gatsby in the past year.

@sidharthachatterjee

We can maybe add a gatsby clean to the cli that deletes both the folders but generally, @jonniebigodes makes a good point that these folders ought not to be touched since they are owned by gatsby .

Apologies for the not very helpful error messages. We are working towards improving this.

@hackhat

@sidharthachatterjee Ok, cool. Thanks.

@pieh I’m not sure how would that work when you build for dev vs build for prod. Looks like the prod build uses dev assets. I don’t feel very safe about it, but looks like has no problems for now.

@jonniebigodes I think the code should do its best to avoid developer mistakes. For example rememering to delete .cache before you build is an antipattern. Why not delete the .cache folder when you run the build automatically? You will do one mistake at one point.

@gatsbot
gatsbot
bot

added
the

stale?

Issue that may be closed soon due to the original author not responding any more.

label

Feb 7, 2019

@gatsbot

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label «not stale» to keep this issue open!

Thanks for being a part of the Gatsby community! 💪💜

@gatsbot

Hey again!

It’s been 30 days since anything happened on this issue, so our friendly neighborhood robot (that’s me!) is going to close it.

Please keep in mind that I’m only a robot, so if I’ve closed this issue in error, I’m HUMAN_EMOTION_SORRY. Please feel free to reopen this issue or create a new one if you need anything else.

Thanks again for being part of the Gatsby community!

@lionelbarrow

I just ran into this as well.

For future people: the tl; dr is that when making a fresh build, delete both public and .cache.

elitan, jaynetics, AriaFallah, tjmcewan, FredericMartinez, OArnarsson, matt-oakes, edsu, barbalex, clarmso, and 23 more reacted with thumbs up emoji
Jalapina reacted with thumbs down emoji

@DSchau

@lionelbarrow could you share some context as to why you deleted the public folder to begin with?

We’re trying to track down caching issues in #11747, so any insight you have would be invaluable—particularly if it’s reproducible! Thanks!

@sidharthachatterjee

Also side note: You can also use gatsby clean which will delete both for you. Released in gatsby-cli@2.4.11

@andrecalvo

Not sure if it’s related but I found this issue ^ while googling a solution…

I am running npm run serve after gatsby clean however I get this error when trying to view localhost:9000.

Error: ENOENT: no such file or directory, stat '/xxx/xxx/gatsby-site/public/404.html'

newyumi, spierr, felixakiragreen, gallelloit, liamjohnston, hal-efecan, misakimichy, bethshook, jingoldby, seanlandsman, and 2 more reacted with thumbs up emoji

@the-main-thing

Not sure if it’s related but I found this issue ^ while googling a solution…

I am running npm run serve after gatsby clean however I get this error when trying to view localhost:9000.

Error: ENOENT: no such file or directory, stat '/xxx/xxx/gatsby-site/public/404.html'

Same here

@the-main-thing

But gatsby develop works well.

@the-main-thing

After executing npm run build gatsby serve started to working properly.
What I did:

  1. npm install — warnings
  2. gatsby serve — error
  3. delete public and .cache
  4. gatsby serve — error
  5. gatsby develop — ok
  6. npm run build — ok
  7. gatsby serve — ok

@danielpuehringer

If I run gatsby start and then run gatsby build it fails. If I delete the cache folder and run gatsby build it works.

Hi, I had the same Error. It occured after successfully building the project. 5min later when I was trying to execute gatsby develop I ran into the same error message «Error: ENOENT: no such file or directory, open ‘C:…publicstaticd655path—index-6a9-M35H41xhcRuRW1Ovpq3cs1Xmo.json'»

So gatsby develop fails with this exception and gatsby build does not finish at all because «Building static HTML for pages» does not stop.

Occurring Error: Error: ENOENT: no such file or directory, open 'C:...publicstaticd655path---index-6a9-M35H41xhcRuRW1Ovpq3cs1Xmo.json'
Solution: by deleting all the files in the .cache folder I was able to fix those errors :)

@smakosh

Having the same issue here even after deleting both the public and .cache folders, I even removed the node_modules and re-installed them

@alexmcode

Hi. Having the same error. Also I get this output every time I run gatsby serve:

error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  85 | ]);
  86 |
> 87 | proxyRequestMethods(Index, '_index', IDBIndex, [
     | ^
  88 |   'get',
  89 |   'getKey',
  90 |   'getAll',


  WebpackError: ReferenceError: IDBIndex is not defined

@alexpreiss

Hi. Having the same error. Also I get this output every time I run gatsby serve:

error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  85 | ]);
  86 |
> 87 | proxyRequestMethods(Index, '_index', IDBIndex, [
     | ^
  88 |   'get',
  89 |   'getKey',
  90 |   'getAll',


  WebpackError: ReferenceError: IDBIndex is not defined

Are you trying to use Firebase?

@barbalex

@barbalex

Well, maybe you have to log in for that community. Here the long story short:

  • for a large update I had to synchronize SQL-changes and app deployment
  • I built the app, applied the sql changes then deployed on zeit/now as hundreds of times before
  • unfortunately the deployment hit a 10’000 file limit
  • my app was broken, it was 23.00 at night after a hard days work and I had to get things working again
  • I thought: maybe the public folder contains unneeded stuff. Emptied it. Tried to build and hit the errors mentioned in this issue
  • I found this issue, deleted public folder and .cache folder, rebuilt — and found only 600 files in the public folder

Minus 9’400 files!

After this deployment worked again :-)

my app was broken, it was 23.00 at night after a hard days work

Reading this after writing it makes me realize just how bad I had timed this :-|

@Brydom

@kostimarko

Hi. Having the same error. Also I get this output every time I run gatsby serve:

error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  85 | ]);
  86 |
> 87 | proxyRequestMethods(Index, '_index', IDBIndex, [
     | ^
  88 |   'get',
  89 |   'getKey',
  90 |   'getAll',


  WebpackError: ReferenceError: IDBIndex is not defined

Are you trying to use Firebase?

I’m getting the same issue and I’m using firebase

@epgui

Our production build will always fail exactly this way:

 ~/Developer/dooly/marketing   gp-boards-landing-page ● ⍟3  yarn run deploy                                                      8.16.0 ⬢
yarn run v1.17.0
$ gatsby build && gulp deploy
success open and validate gatsby-configs - 0.020 s
success load plugins - 1.558 s
success onPreInit - 0.007 s
success delete html and css files from previous builds - 0.072 s
success initialize cache - 0.008 s
success copy gatsby files - 0.083 s
success onPreBootstrap - 0.018 s
Starting to fetch data from Contentful
Fetching default locale
default locale is : en-US
contentTypes fetched 21
Updated entries  0
Deleted entries  0
Updated assets  0
Deleted assets  0
Fetch Contentful data: 383.381ms
success source and transform nodes - 0.976 s
success building schema - 0.728 s
success createPages - 0.089 s
success createPagesStatefully - 0.053 s
success onPreExtractQueries - 0.011 s
success update schema - 0.037 s
success extract queries from components - 0.217 s
success write out requires - 0.006 s
success write out redirect data - 0.002 s
success Build manifest and related icons - 0.094 s
success onPostBootstrap - 0.103 s
⠀
info bootstrap finished - 8.207 s
⠀
success run static queries - 0.002 s
success Building production JavaScript and CSS bundles - 14.427 s
error ENOENT: no such file or directory, open '/Users/gp/Developer/dooly/marketing/public/page-data/404.html/page-data.json'


  Error: ENOENT: no such file or directory, open '/Users/gp/Developer/dooly/marketing/public/page-data/404.html/page-data.json'

⠙ Rewriting compilation hashes
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Unless I delete .cache before I run the same production build command. yarn deploy just runs gatsby build && gulp deploy. If .cache is deleted before the production build runs, there are never any issues.

Environment

  System:
    OS: macOS 10.14.5
    CPU: (4) x64 Intel(R) Core(TM) i5-7267U CPU @ 3.10GHz
    Shell: 5.3 - /bin/zsh
  Binaries:
    Node: 8.16.0 - ~/.nvm/versions/node/v8.16.0/bin/node
    Yarn: 1.17.0 - /usr/local/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v8.16.0/bin/npm
  Languages:
    Python: 2.7.10 - /usr/bin/python
  Browsers:
    Chrome: 75.0.3770.100
    Safari: 12.1.1
  npmPackages:
    gatsby: ^2.11 => 2.11.0
    gatsby-image: ^2.0.25 => 2.1.4
    gatsby-plugin-manifest: ^2.0.13 => 2.1.1
    gatsby-plugin-react-helmet: ^3.1 => 3.1.0
    gatsby-plugin-remove-serviceworker: ^1.0.0 => 1.0.0
    gatsby-plugin-sharp: ^2.0.17 => 2.1.7
    gatsby-plugin-sitemap: ^2.0.3 => 2.1.0
    gatsby-plugin-styled-components: ^3.1.0 => 3.1.0
    gatsby-source-contentful: ^2.0.45 => 2.0.73
    gatsby-source-filesystem: ^2.0.12 => 2.0.41
    gatsby-transformer-remark: ^2.1.12 => 2.4.0
    gatsby-transformer-sharp: ^2.1.10 => 2.1.21

@PolGuixe

We have encountered this issue on a CICD environment where we cache /public and /.cache in order to speed up builds…

If we eliminate the cache then builds will be slow again… 😢

@D3vd
D3vd

mentioned this issue

Jul 20, 2019

@josephkandi

I am having a similar issue using Firebase 6.5.0, WebpackError: ReferenceError: IDBIndex is not defined.

When i change the firebase version to 5.9.0 the build works fine without issues. Anyone solved this when using firebase?

@kostimarko

I fixed this error by switching to http calls rather than trying to call the cloud function from firebase.

@josephkandi

I fixed this error by switching to http calls rather than trying to call the cloud function from firebase.

Am using firebase auth and firestore in my case. I would want to continue using it this way but find a fix that would work on the latest version

@antonioallen

@josephkandi I am having the same issue as well. I’m going to try rolling back to 5.9.0 and see what happens.

@fabianrios

I had the same problem it should be standard to run gastby clean before build to avoid this error
"build": "npm run clean && gatsby build",

@josephkandi

@fabianrios

I had the same problem it should be standard to run gastby clean before build to avoid this error
"build": "npm run clean && gatsby build",

Was your issue related to the firebase package?

@fabianrios

I don’t think so but it got solved as well just by clean before building the same way so many other people have solve it, so the out of the box gatsby build command should include clean and that way a common error could be avoided.

@AAverin

Because this seems to be the thread to discuss IDBIndex is not defined error when building an app with Firebase inside, just want to link a thread to firebase sdk with explanation why this happens.
firebase/firebase-js-sdk#1797

I am not so good with webpack configuration, maybe somebody could come up with a gatsby workaround for the problem? All solutions on the mentioned ticket are not for gatsby

@AAverin

@AAverin

Solved using lazy firebase init explained here #8612

@odinho

Oh my god. I debugged this for a long time. I thought it was the URL global missing. But that was a red herring.

We delete the public folder in our yarn build so it’ll always be fresh, and also so that Hugo + Gatsby and some other scripts can interact fully without eachother.

It’s not unreasonable to think this would be fine.

@roffelsaurus

I was having CI build issues. I was caching /.cache/ but not ./public/ and that caused this error to happen. Keeping both or deleting both will fix this issue as it is appear. I have a small worry though.

I see alot of people here talking about «always cleaning both» but that is definitely a no-go as build time is a critical factor.

So my only option is to keep both, but I fear that will lead to remnants of old builds being deployed with new statics.

The design decision of keeping cached stuff in the build output folder is a weird one. File copy time and disk space is insignificant to most people compared to query speed.

At the very least the error message in this code path should be changed to something like «./.cache was expecting file /page-data.json to be present in public/ folder. If this was deleted, please delete both .cache/ and public/ or run gatsby clean to avoid this issue»

@redconfetti

I had the same issue. Thank you. I had deleted the public folder to troubleshoot an issue with a left over asset displaying, but ran into this error after. After deleting the .cache folder, my issue was resolved.

This was referenced

Jul 17, 2020

@lifeeric

inna

First, you need to know the object in greater depth FILE.Basic notions https://en.cppreference.com/w/cpp/io/c .Actually std::FILE is a pointer that gets a different value of knot when a file is opened by function https://en.cppreference.com/w/cpp/io/c/fopen to read and write you must use the functions https://en.cppreference.com/w/cpp/io/c/fread and https://en.cppreference.com/w/cpp/io/c/fwrite respectively https://en.cppreference.com/w/cpp/io/c/fscanf and https://en.cppreference.com/w/cpp/io/c/fprintf if you want to read in format; all these functions expect to receive a pointer std::FILE to operate on it.Read the file.I see in your code that you open a file in the reading mode (read «r») binaria (binary «b»(c):FILE * usuario = fopen(«usuarios.dat», «rb»);
So the read-to-use function will be std::freadwhich receives four parameters:Memory address to read.Data size to read.Number of data to read.Pointer to std::FILE to read.Therefore, to read your structure you will need:An integer (int) temporary to read numerical data.A temporary character buffer to read text data on.Assuming that before the name and the last name you have kept the length of each one of them, your reading process might look like:int i;
char c[200]{};
usuario u;
std::FILE *f = fopen(«usuarios.dat», «rb»);
// Leemos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
std::fread(&i, sizeof(int), 1, f);
u.id = i;
// Leemos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
std::fread(&i, sizeof(int), 1, f); // Longitud de ‘nombre’
// Leemos en ‘c’ ‘i’ datos de tamaño ‘char’ desde ‘f’.
std::fread(c, sizeof(char), i, f); // ‘nombre’
u.nombre = c;
// Leemos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
std::fread(&i, sizeof(int), 1, f); // Longitud de ‘apellido’
// Leemos en ‘c’ ‘i’ datos de tamaño ‘char’ desde ‘f’.
std::fread(c, sizeof(char), i, f); // ‘apellido’
u.apellido = c;
Write in the file.You must open the file in the script mode (write «w») binaria (binary «b»(by consistency with the above):FILE * usuario = fopen(«usuarios.dat», «wb»);
So the read-to-use function will be std::fwritewhich receives four parameters:Data management to write.Size of data to write.Amount of data to write.Pointer to std::FILE in which to write.Therefore, to write your structure you will need:An integer (int) from which numerical data will be written.Your writing process might look like:int i;
usuario u;
std::FILE *f = fopen(«usuarios.dat», «wb»);
// Escribimos un dato de tamaño ‘int’ en ‘f’.
std::fwrite(&u.id, sizeof(int), 1, f);
// Escribimos un dato de tamaño ‘int’ en ‘f’.
i = nombre.length();
std::fwrite(&i, sizeof(int), 1, f); // Longitud de ‘nombre’
// Escribimos desde ‘nombre.data()’ ‘i’ datos de tamaño ‘char’ en ‘f’.
std::fread(nombre.data(), sizeof(char), i, f); // ‘nombre’
// Escribimos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
i = apellido.length();
std::fwrite(&i, sizeof(int), 1, f); // Longitud de ‘apellido’
// Escribimos desde ‘apellido.data()’ ‘i’ datos de tamaño ‘char’ en ‘f’.
std::fwrite(c, sizeof(char), i, f); // ‘apellido’
All together: by reference.The right thing would be for reading and writing operations to be encapsulated in their own function:void leer_dato(usuario &u, std::FILE *&f)
{
int i;
char c[200]{};
// Leemos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
std::fread(&i, sizeof(int), 1, f);
u.id = i;

// Leemos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
std::fread(&i, sizeof(int), 1, f); // Longitud de ‘nombre’
// Leemos en ‘c’ ‘i’ datos de tamaño ‘char’ desde ‘f’.
std::fread(c, sizeof(char), i, f); // ‘nombre’
u.nombre = c;

// Leemos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
std::fread(&i, sizeof(int), 1, f); // Longitud de ‘apellido’
// Leemos en ‘c’ ‘i’ datos de tamaño ‘char’ desde ‘f’.
std::fread(c, sizeof(char), i, f); // ‘apellido’
u.apellido = c;

}
void escribir_dato(const usuario &u, std::FILE *&f)
{
int i;
// Escribimos un dato de tamaño ‘int’ en ‘f’.
std::fwrite(&u.id, sizeof(int), 1, f);

// Escribimos un dato de tamaño ‘int’ en ‘f’.
i = nombre.length();
std::fwrite(&i, sizeof(int), 1, f); // Longitud de ‘nombre’
// Escribimos desde ‘nombre.data()’ ‘i’ datos de tamaño ‘char’ en ‘f’.
std::fread(nombre.data(), sizeof(char), i, f); // ‘nombre’

// Escribimos en ‘i’ un dato de tamaño ‘int’ desde ‘f’.
i = apellido.length();
std::fwrite(&i, sizeof(int), 1, f); // Longitud de ‘apellido’
// Escribimos desde ‘apellido.data()’ ‘i’ datos de tamaño ‘char’ en ‘f’.
std::fwrite(c, sizeof(char), i, f); // ‘apellido’

}
Other things to keep in mind.The object std::FILE belongs to the C bookstores, since you have labeled the question as C++, Forget it and don’t use it.. Use the flows (stream) data std::ifstream and std::ofstream.

Я выполнял учебник scotch.io для создания моего первого приложения node и angular. Я видел, что относительные пути — это обычная проблема в Интернете для Error: ENOENT: no such file or directory, которая, насколько я могу судить, такая же, как и в учебнике, поэтому я почему-то не работаю.

Полное сообщение об ошибке:
Error: ENOENT: no such file or directory, stat'/Users/badman/githubRepos/travelGuide/app/public/index.html'
at Error (native)

Моя структура папок находится здесь.
Мой server.js:

// set up web server
var express = require('express');
var app = express();
var bodyParser = require("body-parser");

// routes
require('./app/routes.js')(app);

// listen (start app with node server.js)
app.listen(3000, function() {
  console.log("server going");
})

routes.js:

module.exports = function (app) {

  app.get('*', function (req, res) {
      res.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
  });

};

Любая помощь приветствуется:)

Проблема: в текущем проекте при запущенных вотчерах в 50% случаев изменение файлы выкидывает ошибку:

ENOENT: no such file or directory, stat ‘/home/username/PhpstormProjects/js/bd/src/ts/classes/bd/file_name.ts___jb_tmp___’
at Error (native)

Что это за постфикс `___jb_tmp___` я без понятия. Гугл ничего не находит. Поиск по node_modules — тоже.
Как вообще определить — в сторону какого плагина копать?

Зависимости:

"dependencies": {
    "gulp": "^3.9.1",
    "gulp-include-source": "0.0.5",
    "gulp-livereload": "^3.8.1",
    "gulp-minify": "0.0.10",
    "gulp-plumber": "^1.1.0",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-watch": "^4.3.5",
    "ts-loader": "^0.8.2",
    "typescript-extends": "^1.0.1"
  },
  "devDependencies": {
    "browser-sync": "^2.12.3",
    "typescript": "^1.9.0-dev.20160422",
    "webpack": "^2.1.0-beta.6",
    "webpack-stream": "^3.2.0"
  }

Таск JS в gulp:

gulp.task('js', function() {
   gulp.src('src/ts/bd.ts')
       .pipe(plumber())
       .pipe(sourcemaps.init())
       .pipe(webpack({
           debug: true,
           devtool: 'source-map',
           module: {
               loaders: [
                   {
                       test: /.ts$/,
                       loader: 'ts-loader',
                       exclude: /node_modules/
                   }
               ]
           },
           output: {
               filename: 'bd.js',
               library: "LibraryName",
               libraryTarget: "var"
           },
           plugins: [
               new ProvidePlugin({
                   __extends: 'typescript-extends'
               })
           ],
           resolve: {
               extensions: ['', '.ts', '.webpack.js', '.web.js', '.js'],
               modulesDirectories: ['node_modules', '.']
           }
       }))
       .pipe(minify())
       .pipe(sourcemaps.write())
       .pipe(gulp.dest('dist/js/'))
       .pipe(reload({stream: true}));
});

Вотчеры и сервер в Gulp

var config = {
    server: {
        baseDir: "./dist"
    },
    host: 'localhost',
    port: 9005,
    ui: {
        port: 8080,
        weinre: {
            port: 9090
        }
    },
    logPrefix: "prefix"
};

gulp.task('watch', function(){
    watch('src/ts/**/**', function(event, cb) {
        gulp.start('js');
    });
    watch('src/*.html', function(event, cb) {
        gulp.start('html');
    });
});

gulp.task('webserver', function () {
    browserSync(config);
});

Понравилась статья? Поделить с друзьями:
  • Error enoent no such file or directory scandir
  • Error enoent no such file or directory open etc ksc web console setup json
  • Error enoent no such file or directory lstat index pug
  • Error english cover
  • Error endl was not declared in this scope