upload file in nodejs - javascript

I am tring to upload a file with NodeJs here is my code.
app.post('/upload',urlencodedParser, function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
var sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv(__dirname + '/upload', function(err) {
if (err)
return res.status(500).send(err);
console.log('File uploaded!');
});});
The promblem is tha i get that error.
/path_of_my_pc/node_modules/fileupload/lib/modules/file.js:23
throw error
^
Error: EACCES: permission denied, mkdir '/upload'
at Error (native)
The file where the all the code is, have all permission.

The error is about 'fileupload' module which is not used in this code. So if you are sure about using it, give all needed permissions to this project. But as you can see here it's better to use for example 'busboy' for uploading files

change permission
Ex#
sudo chown -R $USER:$USER /var/www/yourSiteName
sudo chmod -R 755 /var/www

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?

I am trying to execute a file in sh with nodejs but the console tells me that the file cannot be found

This is the code that i found on the internet:
const { exec } = require('child_process');
var yourscript = exec('sh launch.sh', (error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
and here is my sh file which is in the same file as my previous code:
echo "Hi There!"
but each time I run the program the console shows me:
exec error: Error: Command failed: sh launch.sh
sh: 0: Can't open launch.sh
Can somebody help me with my code please?
First, you seem to have a file permissions issue, so to fix that, start by setting the file permissions for the user as the user needs execution permissions:
chmod 755 launch.sh
Second, the code you found online is using "exec" that is now deprecated in favour of builtin child_process.execFile. So, for your needs the code would look a bit like:
var child_process = require('child_process');
child_process.exec('sh launch.sh', function(error, stdout, stderr){
console.log(stdout);
});
This should help to get started! The inner command sh launch.sh should be executable in the command line, directly, so tested without running the main host or nodejs script! Type the command in your CLI and press enter! Alternatively to calling sh launch.sh do /bin/sh launch.sh
Of course, you might want to look at docs to improve the implementation and fully understand file permissions under your OS, what sh means and finally child_process.exec.
https://www.linux.com/tutorials/understanding-linux-file-permissions
https://en.wikipedia.org/wiki/Bourne_shell
https://nodejs.org/api/child_process.html

Rename return "EPERM: operation not permitted" in JavaScript

In my windows server, I found the fs.rename function always return the below error:
error code is Error: EPERM: operation not permitted, rename 'C:\javascript\nodejs\a.txt' -> 'C:\javascript\nodejs\b.txt'
The below are the test code:
var fs = require('fs');
fs.writeFileSync('a.txt',"This is a file")
fs.writeFileSync('b.txt',"This is another file")
fs.rename('a.txt','b.txt',function (err) {
console.log("error code is " + err);
});
var text = fs.readFileSync('b.txt', "utf-8");
console.log(text)
However, in the current folder, I do see the original file "a.txt" as well as the new renamed file "b.txt".
fs.rename is just a wrapper to rename, and according to rename docs:
EPERM or EACCES
The directory containing oldpath has the sticky bit (S_ISVTX)
set and the process's effective user ID is neither the user ID
of the file to be deleted nor that of the directory containing
it, and the process is not privileged (Linux: does not have
the CAP_FOWNER capability); or newpath is an existing file and
the directory containing it has the sticky bit set and the
process's effective user ID is neither the user ID of the file
to be replaced nor that of the directory containing it, and
the process is not privileged (Linux: does not have the
CAP_FOWNER capability); or the filesystem containing pathname
does not support renaming of the type requested.
You probably have no permissions to delete the file or the target file name already exists.
After huge struggle found the solution for me .. 👍
"Create new folders"
mkdir E:\Buildagent\npm
mkdir E:\Buildagent\npm-cache
"move npm prefix and the cache"
robocopy c:\Users\the-build-user\AppData\Roaming\npm E:\Buildagent\npm
robocopy c:\Users\the-build-user\AppData\Roaming\npm-cache E:\Buildagent\npm-cache /E /MOVE
"Update the npm config for prefix and cache"
npm config set prefix E:\Buildagent\npm
npm config set cache E:\Buildagent\npm-cache
https://alastaircrabtree.com/fixing-intermittant-eperm-operation-not-permitted-on-npm-install/

Node.js: Error trying to use shell command that interacts with files

I am trying to use pngquant after I have uploaded images to my Node.js application.
I am running the following code after upload:
if (pngFiles.length) {
console.log('PNG Files Ready for Processing: ', pngFiles);
pngFiles.forEach(function(file) {
console.log(file);
exec('pngquant --force ' + file, function(error, stdout, stderr) {
console.log(error, stdout, stderr);
});
});
}
But end up with the following error:
{ [Error: Command failed: error: cannot open /Users/nfento/Projects/jamdeo/public/uploads/mytestcontrollers/92614D43-A55A-4456-9663- ABF90A23D9F5/92614D43-A55A-4456-9663-ABF90A23D9F5_7_tablet.png for reading
] killed: false, code: 2, signal: null } '' ' error: cannot open /Users/nfento/Projects/jamdeo/public/uploads/mytestcontrollers/92614D43-A55A-4456-9663-ABF90A23D9F5/92614D43-A55A-4456-9663-ABF90A23D9F5_7_tablet.png for reading\n'
For every file, if I go into the shell and run
`pngquant /Users/nfento/Projects/jamdeo/public/uploads/mytestcontrollers/92614D43-A55A-4456-9663-ABF90A23D9F5/92614D43-A55A-4456-9663-ABF90A23D9F5_7_tablet.png`
I get a success message, what am I doing wrong here? Does my application need additional access?
Well, the first thing to check when you get the error cannot open <PATH> for reading is check the filesystem permissions including owner, group, mode, and all parent directories. Is your node code running as the same user as when you run the command manually in the shell?
Other note probably not your issue, but in general, be really careful when building up a string to be passed to exec as it is extremely easy to allow bugs and big security vulnerabilities via this type of code. So first, try quoting your file path so if you had a path with a space in it, for example, your code would still work correctly.
exec("pngquant --force '" + file + "'", function(error, stdout, stderr) {

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