Hammas
Hammas

Reputation: 1214

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.

Upvotes: 17

Views: 37427

Answers (3)

Karan Vyas
Karan Vyas

Reputation: 129

Try:

const fs = require('fs');
fs.copyFileSync(src, dest);

Upvotes: 5

peteb
peteb

Reputation: 19418

You can do this using the native fs module easily using streams.

const fs = require('fs');
const path = require('path');

let filename = 'mainisp.jpg';
let src = path.join(__dirname, filename);
let destDir = path.join(__dirname, 'test');

fs.access(destDir, (err) => {
  if(err)
    fs.mkdirSync(destDir);

  copyFile(src, path.join(destDir, filename));
});


function copyFile(src, dest) {

  let readStream = fs.createReadStream(src);

  readStream.once('error', (err) => {
    console.log(err);
  });

  readStream.once('end', () => {
    console.log('done copying');
  });

  readStream.pipe(fs.createWriteStream(dest));
}

Upvotes: 21

alejandromav
alejandromav

Reputation: 943

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.

Upvotes: 14

Related Questions