Here, neither you’re checking the read
permission of your source file nor the write
permission of the destination
directory.
And by the way fs.exists
is marked deprecated in the docs.
I’ve implemented a copyFile
function below. See if it works for you.
const path = require("path");
const fs = require("fs");
// Note I'm using the promised version of fs
const fsp = fs.promises;
async function copyFile(sourceDirPath, destDirPath, filename) {
const sourceFilePath = path.join(sourceDirPath, filename);
const destFilePath = path.join(destDirPath, filename);
try {
await fsp.access(sourceFilePath, fs.constants.R_OK);
await fsp.access(destDirPath, fs.constants.W_OK);
await fsp.copyFile(sourceFilePath, destFilePath);
console.log("File copied successfully.");
} catch (ex) {
if (ex.errno === -2)
console.error(`File "${sourceFilePath}" doesn't exist.`);
else if (ex.errno === -13)
console.error(`Could not access "${path.resolve(destDirPath)}"`);
else
console.error(`Could not copy "${sourceFilePath}" to "${destDirPath}"`);
// console.log(ex);
}
}
copyFile("./", "./output", "file.txt");
My Folder structure:
|- copyFile.js
|- file.txt
|- output/
|-
graceful-fs@4.1.15
Error occurs on Windows 10 whether I am in DOS (Admin mode or not), Powershell (Admin mode or not), or GitBash.
Environment:
npm 6.4.1
node v10.14.2
tsc 3.2.2
Tutorial I am working through: https://gonehybrid.com/ionic-4-appsync-set-up-authentication-with-amazon-cognito-part-5/
I was able to work around this issue by always deleting the dest file when any error occurs and then trying again.
NOTE: You will notice that I also added 10 re-attempts to allow for the chance that files were being locked by virus protection, but that did not seem to be the case in my situation.
FILE: %userprofile%AppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js
`
function wait(ms) {
var start = Date.now(),
now = start;
while (now — start < ms) {
now = Date.now();
}
}
function copyFile(srcStat, src, dest, opts) {
if (typeof fs.copyFileSync === ‘function’) {
console.log(‘———————————-‘);
console.log(‘———————————-‘);
console.log(‘fs.copyFileSync( src=’ + src + ‘,’);
console.log(‘ dest=’ + dest + ‘)’);
let fileCopyDone = false;
let attempts = 0;
do {
try {
attempts++;
console.log('Attempt #' + attempts + '...');
fs.copyFileSync(src, dest)
fileCopyDone = true;
} catch (err) {
console.log('ERROR: fs.copyFileSync: ' + err.message);
if (attempts > 10)
throw err;
wait(300);
if (basicFs.existsSync(dest)) {
console.log('Delete dest file: ' + dest);
try {
basicFs.unlinkSync(dest);
console.log('successfully deleted: ' + dest);
} catch (err) {
console.log('ERROR: basicFs.unlinkSync: ' + err.message);
}
}
}
} while (!fileCopyDone);
console.log('----------------------------------');
console.log('fs.chmodSync(dest=' + dest + ',');
console.log(' srcStat.mode=' + srcStat.mode + ')');
fs.chmodSync(dest, srcStat.mode)
console.log('----------------------------------');
console.log('----------------------------------');
if (opts.preserveTimestamps) {
return utimesSync(dest, srcStat.atime, srcStat.mtime)
}
return
}
return copyFileFallback(srcStat, src, dest, opts)
}
`
Detailed error message:
2018-12-16T18:08:39.503Z — error: uncaughtException: EPERM: operation not permitted, copyfile ‘C:UsersRichaprojectsquiz-appamplifybackendapiquizappbuildschema.graphql’ -> ‘C:UsersRichaprojectsquiz-appamplify#current-cloud-backendapiquizappbuildschema.graphql’ date=Sun Dec 16 2018 12:08:39 GMT-0600 (Central Standard Time), pid=23448, uid=null, gid=null, cwd=C:UsersRichaprojectsquiz-app, execPath=C:Program Filesnodejsnode.exe, version=v10.14.2, argv=[C:Program Filesnodejsnode.exe, C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclibinamplify, push], rss=123424768, heapTotal=99049472, heapUsed=76451904, external=2053595, loadavg=[0, 0, 0], uptime=89738, trace=[column=3, file=fs.js, function=Object.copyFileSync, line=1724, method=copyFileSync, native=false, column=12, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=copyFile, line=85, method=null, native=false, column=12, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=mayCopyFile, line=60, method=null, native=false, column=47, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=onFile, line=53, method=null, native=false, column=32, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=getStats, line=47, method=null, native=false, column=10, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=startCopy, line=37, method=null, native=false, column=10, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=copyDirItem, line=166, method=null, native=false, column=39, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=fs.readdirSync.forEach.item, line=159, method=item, native=false, column=null, file=null, function=Array.forEach, line=null, method=forEach, native=false, column=23, file=C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js, function=copyDir, line=159, method=null, native=false], stack=[Error: EPERM: operation not permitted, copyfile ‘C:UsersRichaprojectsquiz-appamplifybackendapiquizappbuildschema.graphql’ -> ‘C:UsersRichaprojectsquiz-appamplify#current-cloud-backendapiquizappbuildschema.graphql’, at Object.copyFileSync (fs.js:1724:3), at copyFile (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:85:12), at mayCopyFile (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:60:12), at onFile (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:53:47), at getStats (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:47:32),
at startCopy (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:37:10), at copyDirItem (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:166:10), at fs.readdirSync.forEach.item (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:159:39), at Array.forEach (), at copyDir (C:UsersRichaAppDataRoamingnpmnode_modules@aws-amplifyclinode_modulesfs-extralibcopy-synccopy-sync.js:159:23)]
Lynn «Кофеман», здравствуйте, пользуюсь Windows.
app.post("/makeFolder", (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*")
console.log(req.body.files[0])
const id = nanoId(13)
fs.mkdirSync(path.join(__dirname, "uploads", id))
fs.copyFileSync(path.join(__dirname, "uploads", req.body.files[0], "index.json"), path.join(__dirname, "uploads", id))
res.send(JSON.stringify({fuck: true}))
})
Массив я получаю с сайта:
if (counter) {
const xmlhttp = new XMLHttpRequest()
xmlhttp.open("POST", "http://localhost:3000/makeFolder", true)
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
xmlhttp.send(JSON.stringify({files: filesArray}))
}
Ошибка:
Error: EPERM: operation not permitted, copyfile ‘C:Users123Desktopexpress testexpress testuploadsAiVjCyDjjvQsNindex.json’ -> ‘C:Users123Desktopexpress testexpress testuploadsb6cy9BHS9ZehA’
at Object.copyFileSync (fs.js:1991:3)
at C:Users123Desktopexpress testexpress testindex.js:84:6
at Layer.handle [as handle_request] (C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterlayer.js:95:5)
at C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterindex.js:335:12)
at next (C:Users123Desktopexpress testexpress testnode_modulesexpresslibrouterindex.js:275:10)
at serveStatic (C:Users123Desktopexpress testexpress testnode_modulesserve-staticindex.js:75:16)
#node.js #node-modules
Вопрос:
Я пытаюсь скопировать файлы img из одного каталога в другой каталог. Я получаю следующую ошибку Error: EPERM: operation not permitted, copyfile
. Я видел другие сообщения об этой ошибке и пробовал их методы, но ни один из них не кажется полезным.
fs.exists(__dirname `/img/${imgSrc}`, (exists)=>{
if(exists){
let imgPath = __dirname `/img/${imgSrc}`
let destinationFolder = __dirname `/projects/${circuitName}-${fuseName}/${poleNumber}`
fs.copyFile(imgPath, destinationFolder,(err)=>{
if(err){
console.log('Error. Unable to transfer file.', err)
}else{
console.log(`Success - File copied: ${imgSrc}`)
}
} )
}else{
console.log('file does not exist')
}
})
***folder structure***
server folder
- img folder //where I am copying img file from
- project folder//where I want to transfer into
- package.json file
- main server.js file //where I am coding from
Комментарии:
1. Это проблема с разрешением. Убедитесь, что у узла есть доступ к каталогу. Где корень этого? Это под
/var/www
водой ?2. Пожалуйста, ознакомьтесь с обновленным сообщением. Я добавил структуру папок
3. Как говорит @Andy, это разрешения на папку.
4. Попробуй
sudo chmod -R 775 </img/folder and project/folder>
5. Я попробовал это, и там написано, что синтаксис команды неверен
Ответ №1:
Здесь вы не проверяете read
ни разрешение вашего исходного файла, ни write
разрешение destination
каталога.
И, кстати fs.exists
, помечен как устаревший в документах.
Я реализовал copyFile
функцию ниже. Посмотрим, сработает ли это для вас.
const path = require("path");
const fs = require("fs");
// Note I'm using the promised version of fs
const fsp = fs.promises;
async function copyFile(sourceDirPath, destDirPath, filename) {
const sourceFilePath = path.join(sourceDirPath, filename);
const destFilePath = path.join(destDirPath, filename);
try {
await fsp.access(sourceFilePath, fs.constants.R_OK);
await fsp.access(destDirPath, fs.constants.W_OK);
await fsp.copyFile(sourceFilePath, destFilePath);
console.log("File copied successfully.");
} catch (ex) {
if (ex.errno === -2)
console.error(`File "${sourceFilePath}" doesn't exist.`);
else if (ex.errno === -13)
console.error(`Could not access "${path.resolve(destDirPath)}"`);
else
console.error(`Could not copy "${sourceFilePath}" to "${destDirPath}"`);
// console.log(ex);
}
}
copyFile("./", "./output", "file.txt");
Моя структура папок:
|- copyFile.js
|- file.txt
|- output/
|-
Комментарии:
1. Я сделал это, но ничего не вышло. У меня нет на это разрешения, говорит
2. Тогда у вас нет разрешения. Это просто 🙂
3. Нашел решение. Мне нужно было добавить imgSrc также рядом с целевым путем при запуске. Например: файл копирования(imgPath, путь удаления imgSrc, ((ошибка)=>{})
4. Рад, что проблема решена 🙂
Add Answer
|
View In TPC Matrix
Technical Problem Cluster First Answered On
October 4, 2021
Popularity
9/10
Helpfulness
1/10
Contributions From The Grepper Developer Community
Contents
Code Examples
Related Problems
TPC Matrix View Full Screen
Error: EPERM: operation not permitted, copyfile
Comment
0
Popularity
9/10 Helpfulness
1/10
Language
whatever
Source: stackoverflow.com
Tags: operation
whatever
Contributed on Oct 04 2021
Upset Unicorn
5 Answers Avg Quality 5/10
In this post, I’m going to list the most common errors you may encounter while getting started with Angular. For each error, I’m going to explain what it means and how to solve it.
This post is a work in progress and I’m planning to add more errors. If there is an error you encounter often, please let us know by dropping a comment.
Error 1: ‘ng’ is not recognized
When creating a new project with Angular CLI, you may receive the following error:
'ng' is not recognized as an internal or external command.
This error is simply telling you that Angular CLI is either not installed or not added to the PATH. To solve this error, first, make sure you’re running Node 6.9 or higher. A lot of errors can be resolved by simply upgrading your Node to the latest stable version.
Open up the Terminal on macOS/Linux or Command Prompt on Windows and run the following command to find out the version of Node you are running:
node --version
If you’re running an earlier version of Node, head over to nodejs.org and download the installer for the latest stable version.
Once you have installed Node 6.9+, you need to install Angular CLI globally:
npm install -g @angular/cli
Note the -g flag here. This tells NPM that you want to install this package globally so you can run it from any folders on your machine.
Error 2: node_modules appears empty
When you run ng serve, you may receive the following error:
node_modules appears empty, you may need to run `npm install`.
Our Angular applications use a bunch of 3rd-party libraries. These libraries are stored in the node_modules folder inside your project folder. When you create a new project using Angular CLI, these third-party libraries should be installed automatically. However, if you’re using a corrupted or a buggy version of Angular CLI, these libraries are not installed. So, you need to manually install them.
To solve this error, run npm install from the project folder. This command will look at package.json in your project folder. This file includes the list of dependencies of your project. NPM will download and store these dependencies in the node_modules folder.
If you found this post helpful, please share it with others.
If there is an error you’d like me to add to this post, please let me know using the comment box below.
Also, if you want to learn Angular properly from basics to the advanced topics, check out my complete Angular course.
Hi! My name is Mosh Hamedani. I’m a software engineer with two decades of experience and I’ve taught over three million people how to code or how to become professional software engineers through my YouTube channel and online courses. It’s my mission to make software engineering accessible to everyone.
Tags: angular
-
#1
Hi,
i have a new installed PBS with attached a NAS storage, mounted to a local mountpoint (speed of backup is not relevant in this case).
The NAS is mounted with full rw rights as smb share.
After start a Backup from a client on the cluster, i get these error:
Code:
ERROR: VM 117 qmp command 'backup' failed - backup register image failed: command error: inserting chunk on store 'nas' failed for bb9f8df61474d25e71fa00722318cd387396ca1736605e1248821cc0de3d3af8 - fchmod "/mnt/nas-share/proxmox-backup/.chunks/bb9f/bb9f8df61474d25e71fa00722318cd387396ca1736605e1248821cc0de3d3af8.tmp_HCXoez" failed: EPERM: Operation not permitted
On PBS i can see in the storage content, that the VM’s are created but with no data.
I can touch (on PBS CLI) the above file. It will be created.
Bfo
Last edited: Jan 18, 2023
-
#2
the system user backup (on the PBS host) needs to be able to write to the datastore, apparently it can’t..
-
#3
Hello fabian,
thank you for your answer. The permissions of the mounted, local storage are 777 (from the top to the last file).
Uses pbs ACL’s? Which User does run the backup?
I cant see any other user on the system, whos from pbs. The pbs was installed on top of debain bullseye today.
Bfo
Last edited: Jan 18, 2023
-
#4
Which User does run the backup?
The «backup» user. Check cat /etc/passwd
in PBS console to see its UID. I think it was UID 34.
-
#5
Hi,
I think, this cant be the problem.
Like i told above, on the storage are directorys created for each VM *after* i start the backup on the Proxmox Host (not pbs) in my case in
/mnt/nas-share/proxmox-backup/vm (these Directorys have 777 rights).
Also in each of them are subdirectorys with [DateTimeName] and one file «owner» (with content root@pam). So someone has create this dirs and files and have full write access. Also the user «backup» has full write access, tested with
«sudo -u backup touch test.txt» inside /mnt/nas-share/proxmox-backup/vm.
My datastore.cfg look like that:
Code:
datastore: nas
comment
gc-schedule daily
path /mnt/nas-share/proxmox-backup
prune-schedule daily
root@hh-pbs $ sudo -u backup touch /mnt/nas-share/proxmox-backup/.chunks/bb9f/bb9f8df61474d25e71fa00722318cd387396ca1736605e1248821cc0de3d3af8.tmp_HCXoez
l /mnt/nas-share/proxmox-backup/.chunks/bb9f/bb9f8df61474d25e71fa00722318cd387396ca1736605e1248821cc0de3d3af8.tmp_HCXoez
-rwxrwxrwx 1 root users 0 18. Jan 13:20 /mnt/nas-share/proxmox-backup/.chunks/bb9f/bb9f8df61474d25e71fa00722318cd387396ca1736605e1248821cc0de3d3af8.tmp_HCXoez
sudo -u backup rm /mnt/nas-share/proxmox-backup/.chunks/bb9f/bb9f8df61474d25e71fa00722318cd387396ca1736605e1248821cc0de3d3af8.tmp_HCXoez
No errors with the commands above.
for Info: the owner of the files an the storage is «root.users»
Bfo
Last edited: Jan 18, 2023
-
#6
it is the problem for sure — the error states that modifying the permissions failed for lack of permissions..
-
#7
Maybe it’s not permitted because the path gets over 255 chars or something similar on the storage side? Or bad ACLs on the NAS?
-
#8
Hello fabian.,
thanks again. After your answer i changed the mount from smb to nfs … and it worked. So the problem is gone. To help any other with the same problem, it will be nice to show more details of this access rights to the user.
Also thanks for Dunuin’s answer for further investigation.
Best thanks @ all
Bfo
Last edited: Jan 18, 2023
-
#9
the error message already gives you all the details — the operation, the path, and the error. PBS doesn’t get any more information either