How to write to a file using Nodejs? - javascript

I am learning how to write to a file using Nodejs. I tried the below posted example, but I received the below posted error
How can I fix this error?
Code:
var fs = require('fs');
fs.writeFile("c://NodeTest", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Error:
{ [Error: EPERM: operation not permitted, open 'c:\NodeTest']
errno: -4048,
code: 'EPERM',
syscall: 'open',
path: 'c:\\NodeTest' }

You don't have permission to access that file. Try running as administrator or manually changing the permissions on the file

Since it looks like you are using windows, this seems to be a file permissions error. Try running your code as administrator (e.g. right click on the dos command prompt icon and choose "Run as administrator", then try to run your script).

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

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.

upload file in nodejs

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

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!

Categories