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

แชร์
ฝัง
  • เผยแพร่เมื่อ 6 ก.ค. 2024
  • 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 ปีที่แล้ว +12

    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: th-cam.com/play/PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw.html

  • @chotabomjvonychi3485
    @chotabomjvonychi3485 2 ปีที่แล้ว +15

    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 ปีที่แล้ว +4

      Thank you - documentation is always an essential reference 💯

  • @samdavepollard
    @samdavepollard 2 ปีที่แล้ว +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.

  • @codewithkin
    @codewithkin 9 หลายเดือนก่อน +1

    This course is so underrated, thanks for this Dave!

  • @mindurownbussines
    @mindurownbussines 2 ปีที่แล้ว +1

    Thank you Dave
    These tutorials are gold

  • @tf1n
    @tf1n 2 ปีที่แล้ว +3

    Fantastic vanilla Node tutorial. Concise and practical. Thank you, Dave!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

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

  • @kostiantynkarzhanov9216
    @kostiantynkarzhanov9216 9 หลายเดือนก่อน

    The best channel ever! Thank you for the awesome tutorial! 💛

  • @ahmad-murery
    @ahmad-murery 2 ปีที่แล้ว +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 ปีที่แล้ว +2

      I agree with all of the above my friend! Thanks for the comment 💯

  • @loikvokhidov7688
    @loikvokhidov7688 ปีที่แล้ว

    I am loving this series 👍

  • @yuliiashmidt6332
    @yuliiashmidt6332 2 ปีที่แล้ว +1

    nice tutorial! Thanks Dave

  • @jennyaguilar5083
    @jennyaguilar5083 2 ปีที่แล้ว

    I loved this tutorial... Thank you Dave!

  • @arturotrejo5923
    @arturotrejo5923 2 ปีที่แล้ว +1

    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

  • @dorian7215
    @dorian7215 ปีที่แล้ว

    This content is by far the best. Thank you for this labor of love. It's going to change my life.

  • @aamirbinusman8416
    @aamirbinusman8416 2 ปีที่แล้ว +1

    Awesome Explanation.. In an easy to understand manner

  • @daddyknowsbest8832
    @daddyknowsbest8832 ปีที่แล้ว

    Awesome video Dave! Your video helped me.

  • @MueezKhan1
    @MueezKhan1 11 หลายเดือนก่อน

    Thank you!

  • @yamillayicov7256
    @yamillayicov7256 ปีที่แล้ว

    Thank you Dave Gray you're the best

  • @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!

  • @SumitGupta-ys7lb
    @SumitGupta-ys7lb 7 หลายเดือนก่อน

    You saved my life!🎉

  • @codie12
    @codie12 ปีที่แล้ว

    I love your content so much! Looking forward to new Nodejs tutorial videos. Love from Vietnam

  • @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.

  • @RamanKumar-fv5ub
    @RamanKumar-fv5ub ปีที่แล้ว

    Just want to say, GREAT TUTORIAL!!!!, Thank you

  • @bijoy_7168
    @bijoy_7168 2 ปีที่แล้ว +1

    it really helped me.😍

  • @sergiorey2049
    @sergiorey2049 ปีที่แล้ว

    Really really nice!

  • @abdelmonem88
    @abdelmonem88 2 ปีที่แล้ว

    thanks so much for this helpful tutorial

  • @TravinskiyVladislav
    @TravinskiyVladislav ปีที่แล้ว

    Best of the best of the best. Thanks 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.

  • @tejass817
    @tejass817 2 ปีที่แล้ว +1

    Great Content

  • @mma-dost
    @mma-dost 2 ปีที่แล้ว +1

    Great video sir you have explained fs module very clearly and in a very good way. Thanks a lot sir. 🙏🔥😊✅❤️

  • @sonamohialdin3376
    @sonamohialdin3376 2 ปีที่แล้ว

    Amazing tutorial thank you

  • @alirezahekmati7632
    @alirezahekmati7632 2 ปีที่แล้ว +1

    🚀

  • @ericka.robles6538
    @ericka.robles6538 ปีที่แล้ว

    Yoy Save Mi Life with this video!!

  • @DKIBUI
    @DKIBUI 2 ปีที่แล้ว +3

    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 ปีที่แล้ว +1

      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: th-cam.com/video/blBoIyNhGvY/w-d-xo.html Thanks for asking! 💯

    • @DKIBUI
      @DKIBUI 2 ปีที่แล้ว +1

      @@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

  • @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 :)

  • @kenansari
    @kenansari 2 ปีที่แล้ว +1

    Thank you, Dave, it will be how many parts? I love your Node.js serie

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      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 🚀

  • @salehm5413
    @salehm5413 2 ปีที่แล้ว +2

    Thinks

  • @ericka.robles6538
    @ericka.robles6538 ปีที่แล้ว

    Kind Regards!!

  • @MathiArasucrysis
    @MathiArasucrysis 2 ปีที่แล้ว +1

    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 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

    Amaizing video, pity that the source code is not available

  • @diahrongrismore1054
    @diahrongrismore1054 2 ปีที่แล้ว +1

    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 ปีที่แล้ว +1

      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.

  • @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.

  • @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.

  • @andrewclarke6916
    @andrewclarke6916 2 ปีที่แล้ว +4

    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 ปีที่แล้ว +5

      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 ปีที่แล้ว +1

      @@DaveGrayTeachesCode Yep, that's fixed it. It will be interesting to hear if anyone else experiences this problem.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +3

      @@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 ปีที่แล้ว +1

      @@DaveGrayTeachesCode I'll give that a try too.

    • @rajvardhansinghbirani1919
      @rajvardhansinghbirani1919 5 หลายเดือนก่อน

      @@andrewclarke6916, same happened with me.

  • @balazskovacs4955
    @balazskovacs4955 2 ปีที่แล้ว

    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  2 ปีที่แล้ว +1

      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 2 ปีที่แล้ว

      @@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  2 ปีที่แล้ว

      ​ @Balazs Kovacs this tutorial loads formData to the backend: th-cam.com/video/4pmkQjsKJ-U/w-d-xo.html

    • @balazskovacs4955
      @balazskovacs4955 2 ปีที่แล้ว

      @@DaveGrayTeachesCode Thank you, i hope i have my result by the morning :)

  • @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.

  • @sayedashraf9241
    @sayedashraf9241 ปีที่แล้ว

    callback functions, error handling, async await

  • @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.

  • @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.

  • @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  ปีที่แล้ว +1

      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!

  • @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

  • @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!

  • @reezus_
    @reezus_ ปีที่แล้ว

    At 9:30, I didn't understand why readFile completed last. I thought read, write and append were all asynchronous?

    • @reezus_
      @reezus_ ปีที่แล้ว

      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_ ปีที่แล้ว

      I get it now... Thanks Still:)

  • @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

  • @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.

  • @AmitYadav-fn1om
    @AmitYadav-fn1om 2 ปีที่แล้ว +1

    How to read from postman

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      Keep going. This series will get you there although I use ThunderClient instead of Postman. Same concept.

  • @devynity4507
    @devynity4507 6 หลายเดือนก่อน

    20:13

  • @alientec258
    @alientec258 ปีที่แล้ว

    Is that also possible with a button

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      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

  • @rohitgarg3942
    @rohitgarg3942 หลายเดือนก่อน +1

    TOO much Depth 😅