I was trying to copy my files to a new destination using fs and then rename them to like 1.png , 1.txt and so on but i always get an error here is my code :
const fs = require('fs');
const path = require('path')
const dir = 'files/newFiles'
const fileNames = fs.readdirSync('files')
for(let i = 0 ; i < fileNames.length ; i ) {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
if(!fs.existsSync(dir '/image')) fs.mkdirSync(dir '/image');
if(!fs.existsSync(dir '/txt')) fs.mkdirSync(dir '/txt');
}
const ext = path.extname(fileNames[i])
if(ext === '.png') return fs.copyFileSync(fileNames[i], dir '/image/' i ext)
if(ext === '.txt') return fs.copyFileSync(fileNames[i], dir '/txt/' i ext)
}
here is the error message :
Error: ENOENT: no such file or directory, copyfile 'file1.png' -> 'files/newFiles/image/'
CodePudding user response:
I updated my answer. The mistake is just slash and back slash and the fs.copyFileSync() function.
The first parameter should be the filepath. but here in script, it is just filename such as "111.png" where should be such as "C:\files\111.png".
So the solution is that
const fs = require('fs');
const path = require('path')
const dir = 'files\\newFiles'
const fileNames = fs.readdirSync('files')
for(let i = 0 ; i < fileNames.length ; i ) {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
if(!fs.existsSync(dir '\\image')) fs.mkdirSync(dir '\\image');
if(!fs.existsSync(dir '\\txt')) fs.mkdirSync(dir '\\txt');
}
const ext = path.extname(fileNames[i])
if(ext === '.png') return fs.copyFileSync(__dirname "\\files\\" fileNames[i], dir '\\image\\' i ext)
if(ext === '.txt') return fs.copyFileSync(__dirname "\\files\\" fileNames[i], dir '\\txt\\' i ext)
}
Please check it