How to Write in File (User Directory) Using JavaScript

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,

  1. In many case you would use fs.mkdirSync rather than fs.mkdir

  2. It is harmless / has no effect to include a trailing slash.

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

  1. 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.
  2. 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.
  3. To store some information on the client side that is considerably small, you can go for cookies.
  4. 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



Leave a reply



Submit