如何使用NodeJS获取另一个文件夹中文件的绝对文件路径?

huangapple go评论60阅读模式
英文:

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: "." });
};

如何使用NodeJS获取另一个文件夹中文件的绝对文件路径?

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.

huangapple
  • 本文由 发表于 2023年4月19日 19:11:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76053817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定