search
HomeWeb Front-endJS TutorialHow to solve nodejs path problem
How to solve nodejs path problemJun 30, 2018 pm 03:13 PM
nodejspath

This article mainly introduces the solution to the path problem of nodejs. The content is quite good. I will share it with you now and give it as a reference.

A recent development project of the company used nodejs as the backend. In the past two days, I needed to package it for customer demonstration, so I asked a guy from the company to transplant the packaging tool from the previous 3D computer room. After packaging, I found that the project that originally ran well in the development environment could no longer be accessed. There is a problem that the homepage of the project cannot be accessed:

can not get file index.html

express.static

What’s the problem?

The nodejs backend uses express, and index.html is a static file. We know that static files, such as images, CSS, JavaScript files, etc., can be easily hosted through Express's built-in express.static.

Pass the directory where the static resource files are located as a parameter to express.static middleware to provide access to static resource files. For example, assuming that images, CSS and JavaScript files are placed in the public directory, you can use the following code:

 app.use(express.static('public'));

So, find the code in the project and check where the static call is, which is very similar to the above line of code:

 app.use(express.static('public'));

At this point, I have discovered the problem. I told my friends that this problem can be solved without using relative paths. Due to the packaging time limit, I asked my friends to deal with it briefly first. After packaging, I will sort out my thoughts:

app.use(express.static('resource/public'));

Of course, the most important thing is that this problem is not difficult. If you study more, it will be very easy. If the problem is easy to find, this problem will not occur, so friends, please do it yourself.

Well, you read that right, this place is still a relative directory. It will be changed to a better situation in subsequent products.

express.static method analysis

In fact, if the express.static method passes in a relative path, express will convert it by itself For an absolute path, we can check the source code and find the following code in express.js:

exports.static = require('serve-static');

Description static calls the serve-static package, find this package directly, check index.js, you can see the code , Listed below are two important lines

 ...
var resolve = require('path').resolve
...
opts.root = resolve(root)
...

These two lines are the code for express to convert a relative directory into an absolute directory. It can be seen that the resolve method of the built-in object path is ultimately used. Continue reading. .

resolve method of path object

Directly view the api document of this method, as follows: https://nodejs.org/api/path .html#path_path_resolve_paths

The following is an explanation of this method:

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

What does it mean? This method organizes a series of paths or path segments into an absolute path, such as

 path.resolve('/foo','bar');
// return /foo/bar

Please refer to the documentation for detailed instructions. There is a sentence here that requires special attention:

If after processing all given path segments an absolute path has not yet been generated, the current working directory is used.

What does it mean, that is, if all path segments have been processed , and does not generate an absolute path, the current working directory must be used. For example:

 path.resolve('bar');
// 加上 /Users/terry 是当前工作目录, return /Users/terry/bar

A more complex example in the api document (note here when resolving, from right to left, refer to the document for details):

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// if the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

The question now is, what is Current working directory.

nodejs current working directory current working directory

nodejs The current working directory is the directory where Node is started. In other words, whichever directory you enter from to start node will return to that directory.

Note that this directory does not refer to the directory where the js file is located

The current working directory can be obtained through the process.cwd() method.

The following is an example to introduce the current working directory. If you write a js file, test.js, in the /Users/terry/Documents/JSWorkspace directory, there is only one line of code:

console.log(process.cwd());

At this time, if you execute the command under the directory /Users/terry/Documents/JSWorkspace: node test.js, the output is as follows:

 /Users/terry/Documents/JSWorkspace

But if you execute the command under the directory /Users/terry/Documents/: node ./JSWorkspace/test.js, the output result is:

/Users/terry/Documents

So you can see in which directory you execute the node command, and the current directory is that directory.

Returning to the previous packaging issue, since during the development stage, the node command is generally executed directly in the directory where the js file is located, so there is no problem in writing the relative directory relative to the directory of the current js file. .

But after packaging, the execution of node is placed in the upper layer of the js directory. At this time, the relative directory "public" is no longer relative to the js file, but relative to the previous layer. Naturally, this folder cannot be found, and therefore the index.html file under the folder cannot be found. .

How to solve

Solution:

1.在前面已经说过了,改这个相对目录。但这种方法很蹩脚。因为,启动node命令的目录可能会变;而是如果这应该,开发阶段的node命令执行也需要跟着改。 总之不是兼容性很好的方法。

2.直接使用绝对路径。 但是这个绝对路径在不同的机器上又不一样,该如何解决呢?可以考虑使用全局变量__dirname.

全局变量__dirname

查看api文档 https://nodejs.org/api/modules.html#modules_dirname

看到解释如下:

The directory name of the current module. This is the same as the path.dirname() of the __filename。

啥意思呢,及时返回nodejs 的js文件的所在目录。

有了这个变量之后,我们就可以用如下代码解决这个问题。

app.use(express.static(__dirname + '/public'));

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Node.js中路径处理模块path的介绍

如何在NodeJS项目中使用ES6

The above is the detailed content of How to solve nodejs path problem. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),