简体   繁体   中英

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM