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中文网!
相关推荐:
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!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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.

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
