EPERM Error using fs.rename() - javascript

Here is my code:
exports.post_handler = function(req, res) {
var photo = req.files.image;
console.log(photo);
console.log(__dirname);
fs.readFile(photo.path, function(err, data) { //I use the path module to join the image path strings
fs.rename(path.join(__dirname, "public/temp"), path.join(__dirname,"public/images"), function(err) {
if (err) {
console.log(err);
res.redirect("/");
}
else {
console.log("file " + photo.name + "written to uploads folder");
res.redirect("/home");
}
});
});
}
I'm trying to move an uploaded image file from my temp folder to my uploads folder. I'm using the fs module to do this. After granting full permissions to both files to all users on my PC, I'm getting the following error:
{ [Error: EPERM, rename 'dir\public\temp']
errno: 50,
code: 'EPERM',
path: 'dir\\public\\temp' }
I'm not sure what's going wrong here. Anyone have any ideas?

What your code is trying to do is rename the public/temp directory to public/images. public/images presumably already exists, so you're getting that error. In other words, nowhere in there are you moving the image, you're instead 'moving' (renaming) the directory public/temp to public/images.
You have to use photo.path instead. Use it as the first parameter and then perhaps the second parameter should path.join images directory to path.basename(photos.path).

Related

Read file from the current folder

I've node program which should run and during runtime read some hidden file
.env.json or env.json. (not hidden file)
I've tried to print the following in the program which needs to read it:
dirname: /Users/i012344/projects/rs/deploy
fileName: /Users/i012344/projects/rs/deploy/deploy/index.js
process.argv[1]: /Users/i012344/.nvm/versions/node/v11.15.0/bin/yo
My running program called is: deploy/index.js
But I dont need this path as this print the location of the current executable program, I need to read a file from the current folder that I run
my program.
e.g.
/Users/i012344/projects/app1/.env.json
Now I run my program inside the app1 folder and needs to get the content of the .env.json file, how can I do it?
when I print
console.log("process.cwd(): ", process.cwd());
I got "/Users/i012344/projects"
I want: /Users/i012344/projects/app1
when running
let filePath = path.join(__dirname, ".env.json");
console.log("ft: ",filePath);
I got error as it search for it in the wrong place
fs.readFile(filePath, {encoding: "utf-8"}, function (err, data) {
if (!err) {
console.log("received data: " + data);
} else {
console.log(err);
}
});
{ [Error: ENOENT: no such file or directory, open 'Users/i012344/projects/rs/deploy']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path:
'/Users/i012344/projects/rs/deploy/index.js/.env.json' }
I dont understand why it's happen as it's just like to a program which needs to read package.json as the package.json is in some generated project.
I doesnt works also for non-hidden file, not sure what Im missing here..., it should be rather simple, just read file from where your application is running
isn't it possible?

File Failing to copy to another directory (fs.access and copyFile)

I'm trying to copy pdf and/or word documents from one folder into another. The code below works sometimes, but then other times it does not.
app.post('/api/file_archive/:file_name', function (req, res) {
var file_name = req.params.file_name;
var src = 'public/uploads/files/' + file_name;
var dest = 'archived_files/files';
if(file_name != "") {
console.log("Entered fs access");
fs.access(dest, function(err) {
if(err)
fs.mkdirSync(dest);
copyFile(src, path.join(dest, file_name));
res.json({ message: 'file archived!'});
});
};
});
I'm currently receiving this error:
{ Error: ENOENT: no such file or directory, open 'C:\Users\duquetr\Documents\maize-and-blue-brief\public\uploads\files\1495121011192_Letter of Rec for RJ.pdf' at Error (native) errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\\Users\\duquetr\\Documents\\maize-and-blue-brief\\public\\uploads\\files\\1495121011192_Letter of Rec for RJ.pdf' }
I've searched around a bit and I can't seem to find anything that pertains to why this code sometimes works.
Thanks for your help!
Check if the Folder exists, where the file is going to be copied to.
because the copy function doesn't add new Folder. so if you copy from "src/1/2.txt" to "dest", and the dest folder didn't have another folder called "1" inside of it, the copy process for "2.txt" won't work.
Check your src's and also make sure that the code passing the filename to this function works properly!

Nodejs move files without deleting source directory

I am trying to move files from one directory to another using the mv module. The problem is, once the files are moved, the source directory gets deleted. I dont want this, I want only the files that are moved to be deleted from the source directory. The source directory should remain (even if it is empty). Not sure how to do this with the mv module (or if there are any other options).
My code
var pathToPdf = path.join(__dirname, '../pathToPdf/');
` var intermediate = path.join(__dirname, '../intermediate/');
fs.readdir(pathToPdf, function(err, files) {
if (err) return;
files.forEach(function(file){
mv(pathToPdf, intermediate, function(err) {
if(err){
console.log("oops!")
}
});
----move code ---
This code is moving the files to intermediate directory, but the pathToPdf directory gets deleted, which I want to avoid. Please advise.
files.forEach(function(file){
console.log(file)
console.log("pathToPdf", pathToPdf+file)
mv(pathToPdf+file, intermediate+file, function(err) {
if(err){
console.log("oops!")
}
});

ENOENT Error - I'm successfully uploading files but can't move them

I'm successfully uploading files to the temp directory, and want to move them to the directory profile_pictures. It seems like such a simple thing, yet I have been stuck here for an hour!
Pretty simple code to do this with Express and fs:
app.post('/upload', function (req, res, next) {
console.log("User uploading profile picture...");
var tmp_path = req.files.profile_picture.path; // get the temporary location of the file
var ext = path.extname(req.files.profile_picture.name); // get the extension of the file with the path module
var target_path = '/profile_pictures/' + req.body.username + ext; // set where the file should actually exists - in this case it is in the "images" directory
fs.rename(tmp_path, target_path, function (err) { // move the file from the temporary location to the intended location
if (err) throw err;
fs.unlink(tmp_path, function (err) { // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
if (err) throw err;
res.send('File uploaded to: ' + target_path + ' - ' + req.files.profile_picture.size + ' bytes');
});
});
});
But this results in the error:
Error: ENOENT, rename 'tmp/5162-2fftn.jpg'] errno: 34, code: 'ENOENT', path: 'tmp/5162-2fftn.jpg'
The image at top is a screen shot of my SFTP manager connected to the working directory of this app, so clearly the directory does exist!
What's my mistake??
I spent a good couple hours myself tying to address this issue. Take a look here for clarification,
https://github.com/nodejs/node-v0.x-archive/issues/2703
Here the thread that actually pointed me in the right direction,
Move File in ExpressJS/NodeJS
Yes, fs.rename does not move file between two different disks/partitions. This is the correct behaviour. fs.rename provides identical functionality to rename(2) in linux.

Node.js fs.ReadFile always returns error

I want Node.js to read form.html when the domain name is localhost:3000/form, but for some reason, it always gives me an error 500 page.
The content parameter in the callback function of fs.readFile gets undefined, even though the path of the file is correct.
app.get('/form', function(req, res){
fs.readFile('/form.html', function(error, content){
if(error){
// This get's always executed... I don't know why.
// content = undefined.
res.writeHead(500);
res.end();
}
else{
res.writeHead(200, { 'content-type' : 'text/html' });
processFile(content);
res.end(content, 'utf-8');
}
});
});
added error message:
{ [Error: ENOENT, open 'C:\form.html'] errno: 34, code: 'ENOENT',
path: 'C:\form.html' }
Do I have to specify the full path to the file...?
After I removed the / I get this path:
C:\Users\deno_000\form.html
My files are all in the same directory, and on the left side of my editor you can see it:
http://i59.tinypic.com/2eqdp2o.jpg
/ in most file systems = root directory.
Either remove the / or add a dot infront like form.html or ./form.html.
. is the current directory
.. is the parent directory
./form.html = [current directory]/form.html]
The error is similar to file not found.
The html file would need to be in the same folder as the .js node file for this to work. If you have it in another path, use that path. \
Note you can also use:
Path#
Stability: 3 - Stable
This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid.
Use require('path') to use this module.
http://nodejs.org/api/path.html
Had the same problem. Using __dirname fixed it.

Categories