[Node.js] Reading from the File System in Node.js
2023-09-14 08:59:12 时间
There are a handful of ways you can read and write to the File System in Node.js.
We will look at readFileSync
, readFile
, 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)
}
相关文章
- Node.js基本数据处理
- windows 环境下使用 Node.js 访问 SAP OData 遇到 unable to get local issuer certificate
- 如何将高德地图JS API嵌入到HTML网页内
- 不影响开发体验,如何将单体 Node.js 变成 Monorepo
- Node.js安装及环境配置之Windows篇详解编程语言
- Node.js 2017企业用户调查结果发布详解编程语言
- Linux上部署Node实现更多功能(linux安装node)
- 版本Linux下查看Node版本号的方法(linux查看node)
- Linux环境下配置Node.js(linux配置node)
- Node.js与MongoDB:联手打造高效应用(node与mongodb)
- 利用 JS 实现 Redis 的连接(js连接redis)
- Node.js和MSSQL数据库的完美结合:使用node mssql模块(node mssql模块)
- PHP读取文件内容代码(txt,js等)
- 鼠标划过实现延迟加载并隐藏层的js代码
- JS操作Array数组的方法及属性实例解析
- JS中判断null、undefined与NaN的方法
- node.js中的buffer.toJSON方法使用说明
- node.js中的fs.writeFileSync方法使用说明
- js中取得变量绝对值的方法