• [Node.js] Reading from the File System in Node.js


    There are a handful of ways you can read and write to the File System in Node.js.

    We will look at readFileSyncreadFile, and a promise based version of readFile.

    Each have there use-cases and we will discuss the pros and cons of each one. For instance readFileSync is a blocking operation which if you were developing a web server with Node.js would be a huge problem. With this project being in the CLI for one user, this is a ok option to consider. On the other hand, readFile is a non-blocking operation that uses promises/callbacks to interact with the file system.

    // Option 1 - Synchronously, OK for small files
    
    import fs from "fs";
    
    const contents = fs.readFileSync("./data.json");
    console.log(contents.toString());
     // Option 2 - With a callback, async
    
     import fs from "fs";
    
     fs.readFile("./data.json", (error, contents) => {
       if (error) {
         console.log(error);
         process.exit(1);
       }
       console.log(JSON.parse(contents.toString()));
     });
    // Option 3 - with a promise
    
    import fs from "fs/promises";
    
    try {
      const contents = await fs.readFile("./data.json");
      console.log(JSON.parse(contents.toString()));
    } catch(err) {
      console.error(err);
      process.exit(1)
    }
  • 相关阅读:
    centos 7 install
    sbt
    maven create project
    java异常个人理解
    (poj1094)Sorting It All Out
    stars
    Following Orders(拓扑排序)
    The House Of Santa Claus(dfs)
    Prime Path(bfs)
    Fence Repair(优先队列容器的应用)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16555668.html
Copyright © 2020-2023  润新知