0

I am trying to use Node's fs library to copy a file in one folder into another folder,
But I'm getting an error of ENOENT: no such file or directory,
But the file is definitely there.

My code is as follows -

let fs = require('fs');
let util = require('util');

let copyFile = async() => {

  try {

    let fsCopyFile = util.promisify(fs.copyFile).bind(fs);
    let files = await fsCopyFile('/Users/aniruddhanarendraraje/Documents/work/pocs/node-crud-app/snippets/sharp/enhancedTest.jpg','/Users/aniruddhanarendraraje/Documents/work/pocs/node-crud-app/snippets/sharp2/enhancedTest.jpg');

  } catch (error) {
    console.error(error);
  }
};

copyFile();

Error -

enter image description here enter image description here

I also tried -

fsCopyFile('./sharp/enhancedTest.jpg','./sharp2/enhancedTest.jpg');

But I'm getting the same error

4
  • 1
    Does the folder sharp2 exists? Commented Jan 14, 2020 at 4:39
  • Your code is working well. Check file path. copy the path name from folder url instead of write the path. Also check target directory path is exist or not Commented Jan 14, 2020 at 4:40
  • @NickLeBlanc sharp2 folder does not exist, I think it should create or overwrite Commented Jan 14, 2020 at 4:53
  • @PrakashT I tried await fsCopyFile('./sharp/enhancedTest.jpg','./sharp2/enhancedTest.jpg'); same error Commented Jan 14, 2020 at 4:54

2 Answers 2

3

here you are using sharp2 directory.But you mentioned in comment sharp2 not exist in the directory.

fsCopyFile doesn't create directory automatically.you should create directory manually.

If you want create directory automatically use Below function:

createDirectory(){
   var dir = '';  /* directory name */

   if (!fs.existsSync(dir)){
     fs.mkdirSync(dir);
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

doh, I had to create a folder, was able to run the code fine, thanks!
1

This is how coping a file using streams.

var fs = require('fs');
fs.createReadStream('source.txt').pipe(fs.createWriteStream('destination.txt'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.