DEV Community

Cover image for Reading and writing files in NodeJS
Onelinerhub
Onelinerhub

Posted on

1 1

Reading and writing files in NodeJS

1. Reading file

const fs = require('fs');

fs.readFile("/tmp/test.txt", "utf8", (err, data) => {
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode
  • fs.readFile( - reads file and returns data in callback function,
  • /tmp/test.txt - path to text file to read,
  • utf8 - encoding to read text in,
  • console.log(data) - log date from file to console.

Open original or edit on Github.

2. Writing file

const fs = require('fs');
fs.writeFile('/tmp/test.txt', 'hi!', (err, data) => {
  console.log(err);
});
Enter fullscreen mode Exit fullscreen mode
  • require('fs') - library to work with file system,
  • /tmp/test.txt - path of file to write,
  • 'hi!' - Data to write to file,
  • console.log(err) - if err is not null, something wrong happened,
  • fs.writeFile( - writes given data to specified file.

Open original or edit on Github.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay