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

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!

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?

Creating folders using fs.mkdir restricts to read-only, so I can't delete folder. Node.js

I have a node.js application where I have a function that will create folders if they don't exist and then create files if it doesn't exist. I also have a function that will delete those files and folders. My problem is that when the folders are created they are created as read-only.
I have already tried to use different file permission modes in the option when creating the folder and made sure to create the files with read/write permission.
This is the code that will create the folders and files:
mkdirp.sync(path.join(__dirname, filePath));
for (let i = 0; i < files.length; i++) {
let filePaths = [] // this list will include the filepath for each file
await fs.open(path.join(__dirname, filePaths[i]), "w+", function(error, fd) {
if (error) {
console.error("error writing image: \n\n" + error);
return;
}
fs.writeSync(fd, files[i].buffer, null, "base64");
});
}
This is the code that will delete folders and files:
await del(filePath);
Expected result should be that the application can create and delete files and folders. The actual result is that the application gets an error message saying this:
{ [Error: EPERM: operation not permitted, unlink "filepath"]
errno: -4048,
code: 'EPERM',
syscall: 'unlink',
path: "filepath"
}
error writing image:
Error: EPERM: operation not permitted, open "filePath"
The application has also been tried on Ubuntu where it runs fine.

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.

EPERM Error using fs.rename()

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).

Categories