英文:
How to get absolute file path of a file inside a folder on another folder using NodeJS?
问题
I want to view index.html file inside client on the controllerClient.js file inside the controller folder using sendFile option. It is working fine on my localhost using the following code but when I try to host it on Vercel, it shows the following error:
Error: ENOENT: no such file or directory, stat '/var/task/client/index.html';
controllerClient.js Code
const viewHome = async (req, res) => {
res.sendFile("/client/index.html", { root: "." });
};
How can I make the code better to make it useful for multi-platform?
英文:
I want to view index.html file inside client on the controllerClient.js file inside controller folder using sendFile option. It is working fine on my localhost using the following code but when i try to host it on vercel it show the following error
Error: ENOENT: no such file or directory, stat '/var/task/client/index.html'
controllerClient.js Code
const viewHome = async (req, res) => {
res.sendFile("/client/index.html", { root: "." });
};
How can I make the code better to make it useful for multi platform ?
答案1
得分: 1
You can use path module to join the current path with __dirname variable which is given by node. __dirname returns the current directory.
const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
Public directory here are the front end files which are sent to the browser. In your case it will be the client
directory.
When using
res.send('index');
above can be used with only the view name instead of full path.
英文:
You can use path module to join the current path with __dirname variable which is given by node. __dirname returns the current directory.
const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
Public directory here are the front end files which are sent to the browser. In your case it will be the client
directory.
When using
res.send('index');
above can be used with only the view name instead of full path.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论