Home Web Front-end JS Tutorial How to solve nodejs path problem

How to solve nodejs path problem

Jun 30, 2018 pm 03:13 PM
nodejs path

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:

1

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

Copy after login
Copy after login

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

1

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

Copy after login
Copy after login

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:

1

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

Copy after login

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:

1

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

Copy after login

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

1

2

3

4

5

...

var resolve = require('path').resolve

...

opts.root = resolve(root)

...

Copy after login

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

1

2

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

// return /foo/bar

Copy after login

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:

1

2

path.resolve('bar');

// 加上 /Users/terry 是当前工作目录, return /Users/terry/bar

Copy after login

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

1

2

3

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'

Copy after login

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:

1

console.log(process.cwd());

Copy after login

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

1

/Users/terry/Documents/JSWorkspace

Copy after login

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

1

/Users/terry/Documents

Copy after login

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文件的所在目录。

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

1

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

Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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 of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles