Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file in public folder of an Express.js App

I have been trying to create a simple html file in the public folder of my Express.js app, but can't get the path right. Can anybody help me out?

Here is the part of my app.js where I configure my static folder:

app.use(express.static(path.join(__dirname, 'public')));

and here's the code I'm using to try to create the index.html file in the public folder:

exports.index = function(req, res){
    var fs = require('fs');
    fs.openSync(__dirname + "/public/static_html/index.html", 'w')
};

However, node.js throw an error:

500 Error: ENOENT, no such file or directory 'C:\nodejs\node_modules.bin\myapp\routes\public\static_html\index.html'

Why is it pointing to the to the public folder inside "routes"?

I would like the path to be:

'C:\nodejs\node_modules.bin\myapp\public\static_html\index.html'

Can anybody help please?

like image 247
Hirvesh Avatar asked Jan 12 '23 19:01

Hirvesh


1 Answers

My guess would be that your directory structure looks like this:

app.js
public/
       static_html/
routes/
       index.js 

And that your exports.index exists in routes/index.js (perhaps it's named differently, but I'm just guessing here).

Since __dirname is relative to the module, it will be ./routes in that file. So you need to go back one level to be able to access public/:

fs.openSync(__dirname + "/../public/static_html/index.html", 'w')
like image 165
robertklep Avatar answered Jan 14 '23 09:01

robertklep