Friday, July 29, 2022
HomeWeb DevelopmentUtilizing the writeFileSync technique in Node.js

Utilizing the writeFileSync technique in Node.js


The Node.js file system module gives a superb variety of strategies to create recordsdata, write to recordsdata, and replace recordsdata. Amongst these strategies, there’s one that may carry out all three capabilities synchronously, which is writeFileSync.

On this article, we are going to have a look at the writeFileSync perform and find out how to use it in Node.js. We are going to cowl the next:

Why is writeFileSync helpful in Node.js?

Earlier than we leap right into a sensible demonstration of the writeFileSync perform, let’s have a look at why we might need to create and write recordsdata synchronously.

Like another synchronous perform in Node, writeFileSync will block the occasion loop till the operation is accomplished or till it fails. In different phrases, it blocks the execution of another statements till its execution fails or completes.

For instance, when a writeFileSync perform known as, each different assertion after it should wait till the perform creates a brand new file or throws an error for not creating a brand new file:

fs.writeFileSync('index.txt', 'Some content material');
console.log('file created');

Within the code above, if the index.txt file is created efficiently, the subsequent line of code will execute. But when it fails, Node will throw an error, supplying you with the chance to catch the error.

Blocking the occasion loop, or most important thread, is basically not a superb follow for real-world functions. It’s thought of a nasty follow in Node as a result of it is going to cut back efficiency and trigger safety dangers.

Creating and writing recordsdata with writeFileSync is barely really helpful for debugging functions, similar to each different synchronous perform in Node. As such, you must use the asynchronous perform writeFile for creating and writing recordsdata in real-world initiatives.

Understanding find out how to use the writeFileSync perform may help you simply get began with the writeFile perform as a result of they’ve comparable parameters, and the one distinction in the way in which they work is in catching and dealing with errors.

The way to use writeFileSync in Node.js

The writeFileSync perform is a reasonably simple fs technique. It takes in three parameters, primarily based on which it creates and writes recordsdata:


Extra nice articles from LogRocket:


  • The file identify or descriptor
  • The information that you just need to write to the file
  • Choices: a string or object you should utilize to specify three further non-compulsory parameters

Of those three parameters, solely two are required. The “choices” parameter is non-compulsory. Within the instance beneath, the file identify is index.txt, and the info to be written to the file is Whats up World!:

>const fs = require('fs');

fs.writeFileSync('index.txt', 'Whats up World!');
console.log('File created');

Not solely does writeFileSync create recordsdata, however it will probably additionally overwrite or append to the info on any present file. Let’s take a better have a look at the parameters used on this perform.

The file identify parameter

You should use writeFileSync in Node to create any file kind — together with a textual content file, an HTML file, JavaScript file, Markdown file, Python file, and so on. — so long as you write the file identify with the appropriate extension. For instance,

fs.writeFileSync('index.txt', 'Whats up World!');

The index.txt file within the instance above will probably be created within the present listing you’re in. You possibly can specify a path to another listing, like so:

fs.writeFileSync('notes/index.txt', 'Whats up World!');

Node will throw an error if the notes listing doesn’t exist already. It’s because the writeFileSync technique can not create a listing in Node.

The information parameter

We have now solely used strings as our knowledge in the entire examples to date, however in real-world initiatives, it’s possible you’ll be coping with knowledge aside from strings. Utilizing the Buffer class in Node is widespread amongst builders, so let’s check out it.

In Node, the Buffer class is a world kind for coping with binary knowledge instantly. The simplest means of developing a brand new Buffer for any knowledge is by allocating a particular dimension of bytes, like so:

const { Buffer } = require('buffer');
const fs = require('fs');
const rawData="Whats up World";
const knowledge = Buffer.alloc(rawData.size, rawData, 'utf8');
fs.writeFileSync('index.txt', knowledge);

The primary parameter of the Buffer.alloc technique represents the scale of the byte. Within the above instance, we used the size of the string.

Utilizing the size of the string isn’t at all times protected, as this quantity doesn’t account for the encoding that’s used to transform the string into bytes. As an alternative, we might use one other Buffer technique, like so:

const rawData="Whats up World";
const knowledge = Buffer.alloc(Buffer.byteLength(rawData, 'utf8'), rawData, 'utf8');

Word that the default encoding for strings is utf8, so we will safely take away the encoding for each strategies:

const rawData="Whats up World";
const knowledge = Buffer.alloc(Buffer.byteLength(rawData), rawData);
console.log(knowledge); // <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
console.log(knowledge.toString()) // Whats up World

A Buffer class could be transformed again to a string with the toString technique. In case you’re solely coping with strings an easier method for strings can be to make use of the Buffer.from(string, encoding) technique:

const rawData="Whats up World";
const knowledge = Buffer.from(rawData, 'utf8');
console.log(knowledge); // <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
console.log(knowledge.toString()) // Whats up World

With the Buffer.from technique, you possibly can simply encode a string, array, or buffer with out having to fret about specifying the scale of the bytes, like within the case of Buffer.alloc. The default encoding for the Buffer.from technique can also be utf8.

The choices parameter

The final parameter of the writeFileSync technique is an object with three non-compulsory properties:

The encoding property has a default of utf8. The encoding of the Buffer class used as the info within the writeFileSync technique will override the encoding right here.

In case you specify a utf8 encoding to your knowledge and mistakenly specify base64 encoding right here, the utf8 will override the base64 encoding. So in case you’re going to usually use the Buffer class to encode your knowledge, you don’t must specify any worth for the encoding property right here.

For instance:

const rawData="Whats up World";
const knowledge = Buffer.from(rawData, 'utf8');
fs.writeFileSync('index.txt', knowledge, { encoding: 'base64' }) // utf8 will override this encoding
const txtFile = fs.readFileSync('index.txt')
console.log(txtFile.toString()) // Whats up World

The mode property units the file mode (permission and sticky bits), and it solely has an impact on newly created recordsdata. The default mode is 0o666.

The flag property controls how the file will probably be created and written on. The default flag is is w, which creates the file (if the file doesn’t exist already) or overwrites no matter knowledge the file has with the brand new knowledge (if the file does exist already).

Different flags are:

  • a: creates the file (if it doesn’t exist) or appends to the prevailing knowledge (if it does exist)
  • ax and wx: creates the file (if it doesn’t exist) or throws an error (if it already exists)

Here’s a full record of the flags in Node.

Catching errors whereas utilizing writeFileSync in Node.js

To catch errors we use the attempt...catch assertion. To point out this instance, we should create a customized error. Assuming we have already got a file, reminiscent of an index.txt file, let’s imagine:

const { Buffer } = require('buffer');
const fs = require('fs');

attempt {
  const rawData="Whats up World";
  const knowledge = Buffer.from(rawData);
  fs.writeFileSync('index.txt', knowledge, { flag: 'ax' });
} catch (e) {
  console.log(e); // will log an error as a result of file already exists
}

This can throw an error as a result of the ax flag solely creates new recordsdata; it can not append to present recordsdata. So, in case you’re making an attempt to jot down to an present file with the ax or wx flags, you’re going to get an error.

Creating new recordsdata primarily based on consumer enter

Let’s say we need to solely create new recordsdata, write to them, and transfer on. For instance, we might have an app for which we need to create a file for each new consumer enter from the terminal, with every file having a novel identifier — the username.

Primarily based on this details about the app’s performance, we have to:

  1. Create a brand new file for each consumer with their username because the distinctive identifier
  2. Alert the consumer to attempt a unique username if the given username already exists

With that, our app code can be as follows:

const { Buffer } = require('buffer');
const fs = require('fs');
const readline = require('readline');
const { stdin: enter, stdout: output } = require('course of');
const rl = readline.createInterface({ enter, output });

// enter username
perform requestUsername() {
  rl.query('Enter username: ', (username) => {
    attempt {
      if (!username) return requestUsername();
      const knowledge = Buffer.from(`Your username is ${username}`);
      fs.writeFileSync(`${username}.txt`, knowledge, { flag: 'ax' });
    } catch (e) {
      if (e.code === 'EEXIST') {
        console.log(`${username} already exists, enter a unique username`);
        return requestUsername();
      }
    }
    rl.shut();
  });
}
requestUsername();

Don’t fear about all the additional particulars right here; the actual takeaway right here is the ax flag and attempt...catch assertion. The ax flag helps us determine if the username already exists, through which case the attempt...catch assertion helps alert the consumer.

Updating recordsdata in Node.js with writeFileSync

We clearly can not replace a file utilizing the w, ax, or wx flags, however what we will use is the a flag. The a flag, as talked about earlier than, not solely appends to a file, but in addition creates the file if it doesn’t exist.

Increasing on our earlier instance, let’s say we need to add to the info of a consumer with out creating a brand new file for that consumer. We’d write the next code:

const { Buffer } = require('buffer');
const fs = require('fs');
const readline = require('readline/guarantees');
const { stdin: enter, stdout: output } = require('course of');
const rl = readline.createInterface({ enter, output });

async perform getUsername() {
  const username = await rl.query('Enter username: ');
  if (!username) return getUsername();

  attempt {
    fs.readFileSync(`${username}.txt`);
    return username;
  } catch (e) {
    if (e.code === 'ENOENT') {
      console.log(
        `Username "${username}" doesn't exist, attempt a unique username`
      );
      return getUsername();
    }
  }
}
async perform updateUserInfo() {
  const username = await getUsername();
  const rawData = await rl.query('Enter consumer information (identify|age|course): ');
  const knowledge = Buffer.from(`n${rawData}n`);
  fs.writeFileSync(`${username}.txt`, knowledge, { flag: 'a' });
  rl.shut();
}
updateUserInfo();

Within the code above, we immediate the consumer for the username and test if a file exists for that consumer. If a file does exist, we request extra data from that consumer after which replace the consumer’s file. Fairly easy.

There’s a comparable flag, r+, that throws an error if a file doesn’t exist, however reads and writes to the file if it does exist. Nonetheless, that flag gained’t match into what we wish right here as a result of it overrides all knowledge within the file slightly than appending to it just like the a flag.

Conclusion

On this article, we discovered find out how to use writeFileSync to create and write recordsdata with Node, which is beneficial for debugging.

We noticed find out how to move in knowledge with the Buffer class utilizing two widespread strategies, find out how to management how the file will probably be created utilizing flags, and likewise find out how to catch errors.

As talked about, with what you’ve discovered to date, you too can simply get began with utilizing writeFile (creating recordsdata asynchronously). The one distinction between writeFile and writeFileSync is in catching and dealing with the errors; in any other case, all parameters talked about can be found in each capabilities.

Completely satisfied hacking, and thanks for studying.

200’s solely Monitor failed and gradual community requests in manufacturing

Deploying a Node-based net app or web site is the straightforward half. Ensuring your Node occasion continues to serve sources to your app is the place issues get harder. In case you’re occupied with making certain requests to the backend or third occasion providers are profitable, attempt LogRocket. https://logrocket.com/signup/

LogRocket is sort of a DVR for net and cellular apps, recording actually the whole lot that occurs whereas a consumer interacts together with your app. As an alternative of guessing why issues occur, you possibly can mixture and report on problematic community requests to shortly perceive the basis trigger.

LogRocket devices your app to file baseline efficiency timings reminiscent of web page load time, time to first byte, gradual community requests, and likewise logs Redux, NgRx, and Vuex actions/state. .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments