简体   繁体   English

在Express.js应用程序的公用文件夹中创建一个文件

[英]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. 我一直在尝试在我的Express.js应用程序的公共文件夹中创建一个简单的html文件,但无法获得正确的路径。 Can anybody help me out? 有人可以帮帮我吗?

Here is the part of my app.js where I configure my static folder: 这是我配置静态文件夹的app.js的一部分:

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: 这是我用来尝试在公用文件夹中创建index.html文件的代码:

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

However, node.js throw an error: 但是,node.js会抛出错误:

500 Error: ENOENT, no such file or directory 'C:\\nodejs\\node_modules.bin\\myapp\\routes\\public\\static_html\\index.html' 500错误:ENOENT,没有这样的文件或目录'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' '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). 并且你的exports.index存在于routes/index.js (也许它的命名方式不同,但我只是在这里猜测)。

Since __dirname is relative to the module, it will be ./routes in that file. 由于__dirname是相对于模块的,因此它将是该文件中的./routes So you need to go back one level to be able to access public/ : 所以你需要回到一个级别才能访问public/

fs.openSync(__dirname + "/../public/static_html/index.html", 'w')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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