search
HomeWeb Front-endJS TutorialHow to solve nodejs path problem

How to solve nodejs path problem

Jun 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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software