Reading and Writing Files with Node.js | Node JS Beginners Tutorial

  Рет қаралды 59,168

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Reading and writing files with Node.js is easy after you learn the Node JS file system module. In this Node beginners tutorial, you will learn how to read, write, update and delete files with Node.js. You will also learn how to create readable and writeable streams of data with Node.
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 This lesson is part of a Node.js for Beginners tutorial series playlist:
• Node.js Tutorials for ...
Reading and Writing Files with Node.js | Node JS File System Tutorial
(00:00) Intro
(00:05) Welcome
(00:15) Overview
(00:33) Use the NodeJS docs
(01:50) How to read a file with Node.js
(03:53) How to handle uncaught errors
(04:52) Async example
(06:01) Path module
(07:17) How to write to a file with Node.js
(08:48) How to update a file with Node.js
(10:01) Nested operations
(11:31) Callback hell
(13:32) fsPromises
(16:02) Replace Callback hell with Async Await
(18:50) How to delete a file with Node.js
(20:09) Readstream for large files
(21.25) Writestream for large files
(22:15) Stream data listener
(23:19) Piping data streams
(24:04) How to create a directory with Node.js
(25:14) How to check if a file or directory exists
(27:03) How to remove a directory with Node.js
📚 References:
Node.js Official site: nodejs.org
✅ Follow Me:
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about creating, reading, writing, updating and deleting files in Node.js helpful? If so, please share. Let me know your thoughts in the comments.
#node #js #files

Пікірлер: 122
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
In this Node.js tutorial, we'll explore the File System (fs) common core module. You will see examples of all CRUD (create, read, update and delete) operations for files in Node.js. You will also learn about the asynchronous nature of Node.js and how to avoid "callback hell" by using fsPromises. This tutorial is part of a Node.js for Beginners tutorial series. See the full playlist here: kzbin.info/aero/PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw
@chotabomjvonychi3485
@chotabomjvonychi3485 2 жыл бұрын
It's refreshing to see a tutorial where someone mentions documentation they are using. Most of the times it's "let's put this absolutely cryptic line of code here because I said so".
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you - documentation is always an essential reference 💯
@codewithkin
@codewithkin 8 ай бұрын
This course is so underrated, thanks for this Dave!
@kostiantynkarzhanov9216
@kostiantynkarzhanov9216 8 ай бұрын
The best channel ever! Thank you for the awesome tutorial! 💛
@loikvokhidov7688
@loikvokhidov7688 Жыл бұрын
I am loving this series 👍
@samdavepollard
@samdavepollard 2 жыл бұрын
Super useful. 8 minutes in and you've answered every question I had right now. (JS noob who installed node for the first time this morning as an alternative to doing everything in dev tools. Been wondering for a while if i could read/write files. Kind of crazy how thrilling it is to be sitting here looking at a list of 20 freshly minted random numbers in a simple ol' text file your tutorial taught me how to create.) Many Thanks, once again, for sharing your knowledge. Will be checking out your full node tutorial for sure.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad I could help, Sam! 💯
@devynity4507
@devynity4507 6 ай бұрын
Hey, thanks for this! i am really insterested about how things work in a full developed web application, this thing really helped me!
@mindurownbussines
@mindurownbussines 2 жыл бұрын
Thank you Dave These tutorials are gold
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@jennyaguilar5083
@jennyaguilar5083 2 жыл бұрын
I loved this tutorial... Thank you Dave!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Jenny! 💯
@SumitGupta-ys7lb
@SumitGupta-ys7lb 7 ай бұрын
You saved my life!🎉
@tf1n
@tf1n 2 жыл бұрын
Fantastic vanilla Node tutorial. Concise and practical. Thank you, Dave!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Cameron! 💯
@tf1n
@tf1n 2 жыл бұрын
Any recommendations on serving images from a server? I realize the main options are to store the image in the file system, then use some string identifier in the database or elsewhere to fetch the image, or save the binary data in the database and read it when ready. What’s the best way to serve an image from a GET request?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@tf1n often the API just responds with the image location - possibly in an AWS S3 bucket - and the HTML or other frontend tech pulls the image in from that remote resource.
@yuliiashmidt6332
@yuliiashmidt6332 2 жыл бұрын
nice tutorial! Thanks Dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@ahmad-murery
@ahmad-murery 2 жыл бұрын
learning how to handle system files is very useful when dealing with things such as logging, caching, loading/importing external files into the app (maybe exported from Excel as csv) and many other scenarios , about the uncaught exception (or any similar event available in other languages), I tend to implement it at the final stage in my app development progress so I can immediately notice any exception may occurs (as I forgot to look at the console most of the time), of course I'll be implementing it once my app functionalities are well tested so any error may occur could be due to unpredictable/Uncontrolled external causes (environment settings, server load/crash, file corruption, etc.. ), at this point it's good idea to log what happened there and maybe report it to the developer, Thanks Dave for the great work and I hope to see you in the next video
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I agree with all of the above my friend! Thanks for the comment 💯
@MueezKhan1
@MueezKhan1 11 ай бұрын
Thank you!
@dorian7215
@dorian7215 Жыл бұрын
This content is by far the best. Thank you for this labor of love. It's going to change my life.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@baxtables
@baxtables 11 ай бұрын
Loved the tutorial, it'd be nice if you could show us how to stream huge data from backend to frontend in a mern app.
@yamillayicov7256
@yamillayicov7256 Жыл бұрын
Thank you Dave Gray you're the best
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@aamirbinusman8416
@aamirbinusman8416 2 жыл бұрын
Awesome Explanation.. In an easy to understand manner
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 💯
@daddyknowsbest8832
@daddyknowsbest8832 Жыл бұрын
Awesome video Dave! Your video helped me.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad to hear it!
@TinyMaths
@TinyMaths Жыл бұрын
Thanks for the explanation about why it's better to have the use appened file inside the write file function. I've seen it done before but didn't know why it might be useful. I didn't realize append file was capable of writing a new file also; so now it makes sense to have it operate 'after' write file.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@codie12
@codie12 Жыл бұрын
I love your content so much! Looking forward to new Nodejs tutorial videos. Love from Vietnam
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! And hello 👋 to Vietnam!
@arturotrejo5923
@arturotrejo5923 2 жыл бұрын
I applied this tutorial to read a JSon file and it worked well! Thank you Dave, you really made this task simple and easy to understand!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad it helped! 🚀
@archanaknayanar2500
@archanaknayanar2500 Жыл бұрын
Hi , did you use this tutorial to work with bulk json files or just a single json?
@arturotrejo5923
@arturotrejo5923 Жыл бұрын
@@archanaknayanar2500 Hi, I used a single json file
@TravinskiyVladislav
@TravinskiyVladislav Жыл бұрын
Best of the best of the best. Thanks you
@RamanKumar-fv5ub
@RamanKumar-fv5ub Жыл бұрын
Just want to say, GREAT TUTORIAL!!!!, Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're very welcome!
@bijoy_7168
@bijoy_7168 2 жыл бұрын
it really helped me.😍
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad to hear it! 💯
@abdelmonem88
@abdelmonem88 2 жыл бұрын
thanks so much for this helpful tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're very welcome! 💯
@mma-dost
@mma-dost 2 жыл бұрын
Great video sir you have explained fs module very clearly and in a very good way. Thanks a lot sir. 🙏🔥😊✅❤️
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! 💯🚀
@sergiorey2049
@sergiorey2049 Жыл бұрын
Really really nice!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad it helped!
@sonamohialdin3376
@sonamohialdin3376 2 жыл бұрын
Amazing tutorial thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Sona! 💯
@sonamohialdin3376
@sonamohialdin3376 2 жыл бұрын
@@DaveGrayTeachesCode Thank you Dave
@tejass817
@tejass817 2 жыл бұрын
Great Content
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 💯
@kenansari
@kenansari 2 жыл бұрын
Thank you, Dave, it will be how many parts? I love your Node.js serie
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome 🙏 I have at least 3 more tutorials before adding in the Express JS framework.
@kenansari
@kenansari 2 жыл бұрын
@@DaveGrayTeachesCode thank u , will u add mongodb part also? :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@kenansari yes, that will come after Express JS 🚀
@DKIBUI
@DKIBUI 2 жыл бұрын
You make really good tutorials. I have been using Nodejs and express for about six months and for the most part I understand how it works and I love using it. I know I will learn a lot from these series about native Nodejs. For some reason I don't really get errors in Javascript or Nodejs or even express. There are exceptions, errors, handled errors, uncaught exceptions, error handlers and then you add try and catch to that mix and the whole thing is so confusing. Personally this is the most difficult concept to understand in Javascript. Is there a resource you could point me to that would help clear the confusion or maybe that's a tutorial idea for you. Kind regards
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I agree. Errors are no fun and can be confusing. Handling errors in NodeJS could be a tutorial topic, but overall, I was good with showing how the docs say to catch uncaught errors and give an example of try / catch here. For Vanilla Javascript, I have a short tutorial on handling errors, too: kzbin.info/www/bejne/mJ2loHyvg816rLs Thanks for asking! 💯
@DKIBUI
@DKIBUI 2 жыл бұрын
@@DaveGrayTeachesCode Thank you for the prompt reply. I will watch the video from this link. I really appreciate. Hopefully I get around Nodejs errors before your tutorial but I am sure I would watch your take on it. Thanks a million
@ericka.robles6538
@ericka.robles6538 Жыл бұрын
Yoy Save Mi Life with this video!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Happy to help! 💯
@Idiomeme_com
@Idiomeme_com Жыл бұрын
Very nice, thank you. At the end with an if-else would be enough? Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you - I need a timestamp to reference a specific point in the video :)
@salehm5413
@salehm5413 2 жыл бұрын
Thinks
@MathiArasucrysis
@MathiArasucrysis 2 жыл бұрын
Thanks for your useful content, i have quick question, how to read a docx file source and create a new file in local directory for download.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I haven't used it, but you might try this Github repo. It looks useful for your docx question and has specific examples in NodeJS: github.com/mwilliamson/mammoth.js
@piotrekjazz1287
@piotrekjazz1287 2 жыл бұрын
Amaizing video, pity that the source code is not available
@ericka.robles6538
@ericka.robles6538 Жыл бұрын
Kind Regards!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
🙌
@jamshidtashkent1976
@jamshidtashkent1976 Жыл бұрын
Hello. Many thanx for such a wonderful video. Could you explain, please, this data[, options]. Why is comma insight [ ] ? what does this mean ?
@dj_chateau
@dj_chateau 10 ай бұрын
Anything within the square brackets is considered optional when invoking that function/method. In that instance it's saying if you don't use the options parameter, then the comma isn't needed either.
@balazskovacs4955
@balazskovacs4955 Жыл бұрын
Great video Dave, can you advise how can i append content to a specific line? I want to read the content of HTML file (which works), then identify a specific line that contains then add user input value from a form, and append another 5 lines of specific content after the title line.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You describe a nice JS challenge assignment here. There is more than one way to accomplish this. I won't write the exact code for you, but reference MDN for methods like slice and indexOf. This stackoverflow post may be helpful, too: stackoverflow.com/questions/20817618/is-there-a-splice-method-for-strings
@balazskovacs4955
@balazskovacs4955 Жыл бұрын
@@DaveGrayTeachesCode Thanks for your feedback, i have made it last night already, the script works as I described, mostly thanks to you and some luck that i found the right sources. Now i am working on getting FORMDATA from front end, past it to back end and run the script. If you have any video suggestion on form data sending to back end, especially that file input and text input needs to go in the same package, i appreciate every suggestions
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
​ @Balazs Kovacs this tutorial loads formData to the backend: kzbin.info/www/bejne/aqHQnISgqLB9Y7c
@balazskovacs4955
@balazskovacs4955 Жыл бұрын
@@DaveGrayTeachesCode Thank you, i hope i have my result by the morning :)
@diahrongrismore1054
@diahrongrismore1054 2 жыл бұрын
What is your take on DENO! It started out earlier like a 'gang buster', hot. Now it has slowed down. Have you tried it? do you think it should be used?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Great question! I have not explored Deno. Like many, I waited to see if it would take hold... maybe too many of us waited and kept using Node. I've heard good things, but I currently do not have experience with it.
@alirezahekmati7632
@alirezahekmati7632 2 жыл бұрын
🚀
@sayedashraf9241
@sayedashraf9241 Жыл бұрын
callback functions, error handling, async await
@andrewclarke6916
@andrewclarke6916 2 жыл бұрын
Well, this is a bit of a conundrum. At 27:58, the creation then deletion of the 'new' directory does not work in the same manner. If the 'new' directory doesn't exist, it creates it; if it does already exist, it deletes it. However, it doesn't do both at once, create and then delete it, as in your example. I've checked the code thoroughly and it's identical to yours, Dave. Any idea what might be going on here? It's as if it's evaluating the second if condition BEFORE the creation of the 'new' directory in the first if condition has completed.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
That's a good and interesting question - this could be related to the async nature of Node. I possibly should have addressed it with this example as well as I did early with the files. Try nesting the deletion in the callback of the creation.
@andrewclarke6916
@andrewclarke6916 2 жыл бұрын
@@DaveGrayTeachesCode Yep, that's fixed it. It will be interesting to hear if anyone else experiences this problem.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@andrewclarke6916others may easily experience the same. The async action of creating the directory may or may not complete before the attempt to delete the directory. Nesting in the callback orders the sequence. You could also use fsPromises with async / await as I displayed with file ops.
@andrewclarke6916
@andrewclarke6916 2 жыл бұрын
@@DaveGrayTeachesCode I'll give that a try too.
@rajvardhansinghbirani1919
@rajvardhansinghbirani1919 4 ай бұрын
@@andrewclarke6916, same happened with me.
@madhu8934
@madhu8934 Жыл бұрын
Hi Dave Grey, i want to read JSON file and keep updating the multiple keys in a JSON file. Can you please help how to achieve that
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Keep going in this series. You will see an example of working with a JSON file.
@PavanSibal
@PavanSibal 5 ай бұрын
How about if we have to store file in another directory which is not there under app directory. Thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode 5 ай бұрын
If I remember correctly, this video also shows how to create new directories.
@mohammednoor1330
@mohammednoor1330 Жыл бұрын
hey dave i have a issue with createreadstream it works perfectly iam using csv file for reading but 10 out of 1 time my readstream doesnot read my file i dont know why can u please with me with this it would be really greatful
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I could only guess, but you can ask and provide more information in my Discord here: discord.gg/neKghyefqh Viewers help each other and I answer questions there, too.
@dj_chateau
@dj_chateau 10 ай бұрын
Oddly, I followed your code to the letter and the console.log() ends up writing to the console that the writing was complete before it read from the file and I can't ascertain what is different or why this happens.
@AmitYadav-fn1om
@AmitYadav-fn1om 2 жыл бұрын
How to read from postman
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Keep going. This series will get you there although I use ThunderClient instead of Postman. Same concept.
@codingispower1816
@codingispower1816 Жыл бұрын
What's the difference between writeFile and createWriteStream?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
One uses a stream. I provide examples of both here and am not sure how to explain better than I do in the video. Docs references: writeFile: nodejs.org/dist/latest-v16.x/docs/api/fs.html#fswritefilefile-data-options-callback and writeStream: nodejs.org/dist/latest-v16.x/docs/api/fs.html#class-fswritestream
@alientec258
@alientec258 Жыл бұрын
Is that also possible with a button
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes. However, Node.js runs on the server and while you can build frontend files to be served, it is often just used for the backend (server) code.
@alientec258
@alientec258 Жыл бұрын
thank you for your fast Answer, I would like to write the time with a button in a file. I use xammp, and i have the feeling that nodeJS dont works with my xammp and Apache Installation. I have created an js script with the node js instructions, and one php file with html button, i saw the constellation in a video. But in my case dont works that Method, and i dont know why. Would you make an video for that
@reezus_
@reezus_ 11 ай бұрын
At 9:30, I didn't understand why readFile completed last. I thought read, write and append were all asynchronous?
@reezus_
@reezus_ 11 ай бұрын
And at 11:25 again, I also didn't understand why the result came out in that order. Please help me with this
@reezus_
@reezus_ 11 ай бұрын
I get it now... Thanks Still:)
@shineLouisShine
@shineLouisShine Жыл бұрын
Thank you.. 12:35 - Why when I'm running the exact same code, the read operation doesn't complete before the others? In my case it is: "Write complete - Hello my name is (Reading cimplete) - Rename complete - Append complete. ..?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome, Louis. I cannot be certain what may be different for you, but my only guess is that the fs.rename in your file is not nested inside the fs.appendFile ?
@shineLouisShine
@shineLouisShine Жыл бұрын
​@@DaveGrayTeachesCode Your guess is most definitely make sense and unshockingly - correct. Thanks!
@denmccormik7654
@denmccormik7654 Жыл бұрын
I don't understand: on 28:02 when console logs both "removed" and "created" - how it can be possible? fs.existsSync is sync action so when we enter "IF BODY" we place async callback - mkdir to our async queue. So when we move to the next if statement - our directory does not exist. Am I wrong?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
As you can see the code executed and explained - yes, you are wrong. Just watch at 27:40 where I run the code. It creates the directory and then it removes the directory. I don't think I can demonstrate or explain it better than I have in this video.
@denmccormik7654
@denmccormik7654 Жыл бұрын
@@DaveGrayTeachesCode Thank you Dave. I'm sorry for asking the same question that other people had already asked. You already gave a good explanation in comments below - I just didn't notice.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@denmccormik7654 no worries!
@saraaitali6551
@saraaitali6551 2 жыл бұрын
heyy, i have poblem filesystem.writefile does not create file please help
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I can only suggest to Google your problem. I cannot see your code and can only guess about why it doesn't work. You can rewatch my example that does work as well.
@nameunknown6522
@nameunknown6522 Жыл бұрын
existsSync function is behaving different in my code. Even if you write same code, for the first time it only creates new directory and if you run it again it removes the directory. What's reason behind this strange behavior??
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
It should work as I have demonstrated. You can check the docs here: nodejs.org/dist/latest-v16.x/docs/api/fs.html#fsexistssyncpath
@devynity4507
@devynity4507 6 ай бұрын
20:13
@rohitgarg3942
@rohitgarg3942 25 күн бұрын
TOO much Depth 😅
NPM Node Package Manager Modules | NPM Tutorial for Beginners
23:23
Читаем и записываем файлы в Node.js. Файл в массив и массив в файл
28:01
WebDev с нуля. Канал Алекса Лущенко
Рет қаралды 6 М.
New Gadgets! Bycycle 4.0 🚲 #shorts
00:14
BongBee Family
Рет қаралды 18 МЛН
OMG🤪 #tiktok #shorts #potapova_blog
00:50
Potapova_blog
Рет қаралды 6 МЛН
WHO DO I LOVE MOST?
00:22
dednahype
Рет қаралды 56 МЛН
How to build a REST API with Node js & Express
58:40
Programming with Mosh
Рет қаралды 1,7 МЛН
Reading and Writing Files in Node.js - JavaScript Tutorial
10:01
OpenJavaScript
Рет қаралды 4,5 М.
Node.js Tutorial for Beginners: Learn Node in 1 Hour
1:18:16
Programming with Mosh
Рет қаралды 6 МЛН
Read/Write JSON Files with Node.js
10:27
Hey Node
Рет қаралды 86 М.
A Deep Dive into Node.js Streams | Masterclass
1:15:46
Platformatic
Рет қаралды 7 М.
Passing Data Between Frontend and Backend | Node.js
18:31
Smoljames
Рет қаралды 82 М.
NODE.JS COURSE FROM SCRATCH: Introduction and First Steps
2:18:31
Как работает автопилот на Lixiang L9 Max
0:34
Семен Ефимов
Рет қаралды 16 М.
DC Fast 🏃‍♂️ Mobile 📱 Charger
0:42
Tech Official
Рет қаралды 484 М.
ПОКУПКА ТЕЛЕФОНА С АВИТО?🤭
1:00
Корнеич
Рет қаралды 2,2 МЛН