【Node】Error: ENOENT: no such file or directory, solution

When using fs.renameSync in the node file module to modify the file name, an error is reported: no such file or directory, rename 'file4.txt' -> 'lastFile.txt'.
I used the Run Code method to run the code, and then I reported an error. The error means that there is no such file or directory, but the file and directory do exist, it can only be that the directory is incorrect. Combined with the analysis of the situation, find the following three solutions.

// 1. 导入模块
const path = require('path');
const fs = require('fs');

// 2. 修改文件
fs.renameSync('file4.txt','lastFile.txt')  

// 修改语法:fs.rename('oldFile','newFile') 嗯,然后就导致上图错误。

insert image description here
Solution 1:
Use the command to solve: right-click to display in the file explorer. Enter the command: node 08-common methods of file operation. js can also be solved.

Solution 2:
This is the way to complete the path. The problem is solved, but the path is bloated and needs to be escaped, so it is not particularly good.

	fs.renameSync('D:\\CODER\\04-node\\01-fr文件模块\\file4.txt',"D:\\CODER\\04-node\\01-fr文件模块\\lastFile.txt")

Solution 3:
I think of using string splicing to solve this problem, and then, the error that oldPath must be a string type is reported.

	fs.renameSync(__dirname/'lastFile.txt',__dirname/'file4.txt')

insert image description hereLater, I remembered the ES6 string splicing method, which can indeed be solved.

	fs.renameSync(`${
      
      __dirname}/lastFile.txt`,`${
      
      __dirname}/file4.txt`)

Guess you like

Origin blog.csdn.net/YBJ2022/article/details/129340537