[Node.js] Read a File in Node.js with fs.readFile and fs.readFileSync

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Node.js] Read a File in Node.js with fs.readFile and fs.readFileSync相关的知识,希望对你有一定的参考价值。

We‘ll read a csv file in node.js both synchronously, and asynchronously. The file we‘re reading is a plain text, utf8 file - but you can also use fs.readFile to read a binary file as a buffer. We‘ll look at the differences between readFile and readFileSync, and show examples of how to catch errors if they occur.

 

const fs = require(‘fs‘)

// Async:

fs.readFile(‘data.csv‘, ‘utf8‘, (err, data) => {
  console.log(data)
})


// Sync:

let results

try {
  // (invalid file error example)
  const data = fs.readFileSync(‘nofile.csv‘, ‘utf8‘)
  results = data  
} catch(e) {
  console.log("error", e)
}

console.log("results", results)

 

以上是关于[Node.js] Read a File in Node.js with fs.readFile and fs.readFileSync的主要内容,如果未能解决你的问题,请参考以下文章

[Python] Read from a File in Python

[Python] Read from a File in Python

SQL Script for read information from a csv file in FTP Server

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /d

Read file in Spring

eclipse Archive for required library in project cannot be read or is not a valid ZIP file