javascriptnode.jsnwjsfs-extra

Copy a source file to another destination in Nodejs


I'm trying to copy an image from a folder to another using fs-extra module .

var fse = require('fs-extra');

function copyimage() {
  fse.copy('mainisp.jpg', './test', function (err) {     
    if (err) 
      return console.error(err)
  });
}

This is my directory

and this is the error I get all the time:

Error {errno: -4058, code: "ENOENT", syscall: "lstat", path: "E:\mainisp.jpg", message: "ENOENT: no such file or directory, lstat 'E:\mainisp.jpg'"}

and by changing destination to ./test/ I get this error

Error {errno: -4058, code: "ENOENT", syscall: "lstat", path: "E:\Development\Node apps\Node softwares\Digital_library\mainisp.jpg", message: "ENOENT: no such file or directory, lstat 'E:\Devel… apps\Node softwares\Digital_library\mainisp.jpg'"}

Note: I'm not testing this in browser. It's an Nwjs app and the pics of error attached are from Nwjs console.


Solution

  • Try:

    var fs = require('fs-extra');
    
    fs.copySync(path.resolve(__dirname,'./mainisp.jpg'), './test/mainisp.jpg');
    

    As you can see in the error message, you're trying to read the file from E:\mainisp.jpg instead of the current directory.

    You also need to specify the target path with the file, not only the destination folder.