javascript - 将文件从一个目录复制到另一个目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51862545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:43:50  来源:igfitidea点击:

javascript - Copy file from one directory to another

javascript

提问by user2051533

How could I use javascript to copy C:\folderA\myfile.txtto C:\folderB\myfile.txt? I also have to check to make sure that myfile.txtdoes not already exist in folderB. And finally I have to then rename the new file from myfile.txtto myfile.bak.

我如何使用 javascript 复制C:\folderA\myfile.txtC:\folderB\myfile.txt?我也有检查,以确保myfile.txt不已经存在folderB。最后我不得不然后重命名新文件myfile.txtmyfile.bak

I know javascript can't really be used on a local file system, but if it could be, how would I write this code as simply as possible?

我知道 javascript 不能真正用于本地文件系统,但如果可以,我将如何尽可能简单地编写此代码?

回答by Nuwan Attanayake

in browser side you cannot access local system files.But in server side you could do it as follows.

在浏览器端,您无法访问本地系统文件。但在服务器端,您可以按如下方式进行。

//copyfile.js
const fs = require('fs');

// destination will be created or overwritten by default.
fs.copyFile('C:\folderA\myfile.txt', 'C:\folderB\myfile.txt', (err) => {
  if (err) throw err;
  console.log('File was copied to destination');
});

nodejs has to be installedon your server and then run above script as follows

nodejs 必须安装在您的服务器上,然后按如下方式运行上面的脚本

node copyfile.js