Dynamic route combine

  1. The reason for the problem with the path

    When using the fs module to operate files, if the provided operation path is relative path starting with ./ or ../, the problem of dynamic path splicing error is prone to occur. .

    The reason is that when the code is running, will dynamically splicing out the full path of the operated file based on the directory where the node command is executed. means the actual path is the current directory + relative path.

    If the directory when executing the node command is a folder of JS files, there will be no error. But if the directory has been moved to another location, it is not possible to find the JS file by completing the path after the node command (and before the JS file). That is to say, the completed paths are all invalid.

    1
    2
    cd../ #movement path
    node .\code\prac1.js #Complete the path after the node command, and the result will fail.

  1. Solve dynamic splicing problem with absolute path

    Using an absolute path as the first parameter in fs.readFile() will solve the problem.

    Absolute paths start from a drive letter. In VScode, you can right-click the file and copy the path to get the absolute path, such as D:\Front-end\Nodejs\files\article1.txt .


    But in JS \ is an escape character. So you need to change \ to \\ to get the real path, such as D:\\Front-end\\Nodejs\\files\\article1.txt .


    The disadvantage of this method is that it is not portable and not conducive to maintenance.


  2. __dirname solves the problem of dynamic splicing

    __dirname (double underscore prefix) indicates the directory where the current question is located. The value represented by __dirname does not change with the directory in which the node command is executed. Use __dirname to concatenate the relative path of the file (remove the .) to solve.

    1
    fs.readFile(__dirname + '/files/article1.txt', 'utf8', function(){})

    Note here that the relative path . of the same level should be removed, because . itself is a shorthand for path.

    When using the fs module, you must use the __dirname writing method. For a better writing method, see the path module section.


Share