How to write a file to specific directory in NodeJS?
You have to understand that you can give either absolute path or relative path. Currently what you can do is
fs.writeFile('./niktoResults/result.txt', 'This is my text', function (err) { if (err) throw err; console.log('Results Received');});
Create Directory When Writing To File In Node.js
Node > 10.12.0
fs.mkdir now accepts a { recursive: true }
option like so:
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
or with a promise:
fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);
Notes,
In many case you would use
fs.mkdirSync
rather thanfs.mkdir
It is harmless / has no effect to include a trailing slash.
mkdirSync/mkdir no nothing harmlessly if the directory already exists, there's no need to check for existence.
Node <= 10.11.0
You can solve this with a package like mkdirp or fs-extra. If you don't want to install a package, please see Tiago Peres França's answer below.
how to write file to parent folder with fs of nodejs?
Yes, that should work fine. The main issue I see is that you have no /
between the dirname and the path.
So what you have now is more like:
fs.writeFile('/tmp/module../sibling_dir/file.txt', 'test');
try this:
fs.writeFile(__dirname + '/../sibling_dir/file.txt', 'test');
Saving file in specified directory Node.js
mkdirp(dir)
Returns a promise that is not awaited.
You should call
mkdirp.sync(dir)
Or rewrite your code in an async style.
I would suggest using:
const savePath = require('path').join(__dirname, '/../../images/', email)
to avoid issue related to OS or missing trailing slash.
Write a file into specific folder in node js?
Ensure that the directory is available & accessible in the working directory.
In this case, a function like below needs to be called at the start of the application.
function initialize() {
const exists = fs.existsSync('./niktoResults');
if(exists === true) {
return;
}
fs.mkdirSync('./niktoResults')
}
Is it possible to write data to file using only JavaScript?
Some suggestions for this -
- If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
- If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
- To store some information on the client side that is considerably small, you can go for cookies.
- Using the HTML5 API for Local Storage.
Writing to files in Node.js
There are a lot of details in the File System API. The most common way is:
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
How to create text file through user-defined path
Create a java.io.FileWriter
object first, then create a java.io.PrintWriter
based on that FileWriter
object. Then you can use PrintWriter.print()
to add text to the file:
FileWriter fileWriter = new FileWriter("filename.ext", true);
PrintWriter out = new PrintWriter(fileWriter);
out.print("Text to go in the file");
out.println("Text to go in the file");
Note that you'll need to encase this code in a try-catch
block to handle IOExceptions
:
try {
FileWriter fileWriter = new FileWriter("filename.ext", true);
PrintWriter out = new PrintWriter(fileWriter);
out.print("Text to go in the file");
out.println("Text to go in the file");
} catch (java.io.IOException e) {
//handle
}
out.close(); //Don't forget to close the file when done
Related Topics
How to Detect a Mobile Device With JavaScript
Convert HTML to Data:Text/Html Link Using JavaScript
How to Get the Background Color of an HTML Element
Limit Number of Lines in Textarea and Display Line Count Using Jquery
Prevent Onmouseout When Hovering Child Element of the Parent Absolute Div Without Jquery
How to Use Jquery and Jquery Plugins With Primefaces
Using Selenium to Imitate Dragging a File Onto an Upload Element
Why Is Document.Write Considered a "Bad Practice"
Passing Form Data to Another HTML Page
JavaScript Dom: Find Element Index in Container
How to Escape Quotes in HTML Attribute Values
How to Get Query String Value from Script Path
Jquery CSS Plugin That Returns Computed Style of Element to Pseudo Clone That Element
Set Webkit Keyframes Values Using JavaScript Variable
Why Pass Parameters to CSS and JavaScript Link Files Like Src="../Cnt.Jsver=4.0"