<!DOCTYPE html>
    <html lang="vi" xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://ogp.me/ns#">
    <head>
<title>Cách đọc và ghi file JSON trong Node.js</title>
<meta name="description" content="Cách đọc và ghi file JSON trong Node.js - Savefile - Tin Tức -...">
<meta name="author" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :.">
<meta name="copyright" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :. [admin@nguoicodonvn2008.info]">
<meta name="robots" content="index, archive, follow, noodp">
<meta name="googlebot" content="index,archive,follow,noodp">
<meta name="msnbot" content="all,index,follow">
<meta name="generator" content="NukeViet v4.5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta property="og:title" content="Cách đọc và ghi file JSON trong Node.js">
<meta property="og:type" content="website">
<meta property="og:description" content="Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;cach-doc-va-ghi-file-json-trong-node-js-7713.html">
<meta property="og:site_name" content=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.">
<meta property="og:url" content="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/cach-doc-va-ghi-file-json-trong-node-js-7713.html">
<link rel="shortcut icon" href="https://www.nguoicodonvn2008.info/favicon.ico">
<link rel="canonical" href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/cach-doc-va-ghi-file-json-trong-node-js-7713.html">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/" title="Tin Tức" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/karaoke-dual/" title="Tin Tức - Karaoke Dual" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nhac-tre/" title="Tin Tức - Nhạc trẻ" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tru-tinh/" title="Tin Tức - Trữ tình" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nuoc-ngoai/" title="Tin Tức - Nước ngoài" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/remix/" title="Tin Tức - Remix" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tam-su-tinh-yeu/" title="Tin Tức - Tâm sự tình yêu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tho-suu-tam/" title="Tin Tức - Thơ sưu tầm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/cuoc-song/" title="Tin Tức - Cuộc sống" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/phan-mem/" title="Tin Tức - Phần mềm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/kien-thuc-may-tinh/" title="Tin Tức - Kiến thức máy tính" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/hoc-tap/" title="Tin Tức - Học tập" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tai-lieu/" title="Tin Tức - Tài liệu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/de-thi/" title="Tin Tức - Đề thi" type="application/rss+xml">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css" type="text/css">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/language/vi.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/global.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/site.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/news.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/main.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/custom.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js" type="text/javascript">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css">
<link rel="StyleSheet" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css">
<style type="text/css">
	body{background: #fff;}
</style>
    </head>
    <body>
<div id="print">
	<div id="hd_print">
		<h2 class="pull-left">.&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.</h2>
		<p class="pull-right"><a title=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;." href="https://www.nguoicodonvn2008.info/">https://www.nguoicodonvn2008.info</a></p>
	</div>
	<div class="clear"></div>
	<hr />
	<div id="content">
		<h1>Cách đọc và ghi file JSON trong Node.js</h1>
		<ul class="list-inline">
			<li>Thứ tư - 01/11/2023 10:13</li>
			<li class="hidden-print txtrequired"><em class="fa fa-print">&nbsp;</em><a title="In ra" href="javascript:;" onclick="window.print()">In ra</a></li>
			<li class="hidden-print txtrequired"><em class="fa fa-power-off">&nbsp;</em><a title="Đóng cửa sổ này" href="javascript:;" onclick="window.close()">Đóng cửa sổ này</a></li>
		</ul>
		<div class="clear"></div>
		<div id="hometext">
		</div>
				<div class="imghome">
			<img alt="Cách đọc và ghi file JSON trong Node.js" src="https://st.quantrimang.com/photos/image/2023/10/31/Node-js-JSON-file-7.jpg" width="460" class="img-thumbnail" />
		</div>
		<div class="clear"></div>
		<div id="bodytext" class="clearfix">
			<p style="text-align: justify;"><strong>JSON&nbsp;</strong>là một định dạng dữ liệu cực kỳ phổ biến, vì thế, điều quan trọng bạn cần tìm hiểu tất cả những tác vụ thông dụng. Dưới đây là&nbsp;<strong>cách đọc và ghi file JSON trong Node.js</strong>.</p>

<p style="text-align: justify;"><img alt="Lập trình JSON" data-adbro-processed="true" data-i="0" data-src="https://st.quantrimang.com/photos/image/2023/10/31/Node-js-JSON-file-7.jpg" data-was-processed="true" height="340" src="https://st.quantrimang.com/photos/image/2023/10/31/Node-js-JSON-file-7.jpg" width="650" /></p>

<p style="text-align: justify;">Bạn có thể đọc và ghi file JSON trong Node.js. Toàn bộ việc bạn cần làm là dùng mô đun<strong>&nbsp;fs&nbsp;</strong>làm chi tiết trong hướng dẫn đơn giản dưới đây.</p>

<h2 style="text-align: justify;">Đọc và ghi file JSON trong Node.js</h2>

<p style="text-align: justify;">JavaScript Object Notation hay JSON là một định dạng chuyển đổi dữ liệu gọn nhẹ được dùng phổ biến trong việc trình bày dữ liệu theo cấu trúc. Nó là định dạng dựa trên văn bản, dễ cho con người đọc &amp; ghi, với máy móc thì nó dễ phân tích và tạo dữ liệu.</p>

<p style="text-align: justify;">Khả năng đọc và ghi file JSON theo chương trình trong Node.js cho phép bạn lưu trữ, trao đổi và thao tác dữ liệu theo cấu trúc hiệu quả và dễ dàng. Hãy cùng nhau học cách đọc, ghi và update file JSON bằng mô đun hệ thống file Node.js.</p>

<h2 style="text-align: justify;">Mô đun hệ thống file Node.js</h2>

<p style="text-align: justify;">Hệ thống file Node.js (<strong>fs</strong>) được xây dựng trong Node.js. Nó cho phép bạn tương tác với hệ thống file trên thiết bị. Bạn có thể dùng nó để đọc nội dung, tạo mới và xóa file.</p>

<div style="text-align: justify;"><iframe allowtransparency="true" data-google-container-id="a!2" data-google-query-id="CMzRu_P9ooIDFZUQYAodvC4F0w" data-load-complete="true" frameborder="0" height="0" hspace="0" id="aswift_1" marginheight="0" marginwidth="0" name="aswift_1" sandbox="" scrolling="no" vspace="0" width="694"></iframe></div>

<p style="text-align: justify;">Những phương thức được cung cấp bởi mô đun<strong>&nbsp;fs</strong>&nbsp;có thể là đồng bộ hoặc bất đồng bộ. Các phương thức đồng bộ chặn chạy chương trình của bạn cho tới khi hoạt động của hệ thống file hoàn tất. Những phương pháp này luôn có “Sync” ở cuối tên. Ví dụ,&nbsp;<strong>readFileSync&nbsp;</strong>hoặc&nbsp;<strong>writeFileSync</strong>.</p>

<p style="text-align: justify;">Mặt khác, các phương thức bất đồng bộ không chạy thực thi chương trình và cho phép nó liên tục xử lý những nhiệm vụ khác trong khi triển khai hoạt động hệ thống file. Những phương thức này chấp nhận hàm callback, sẽ chạy khi hoạt động hoàn tất. Ví dụ,&nbsp;<strong>readFile</strong>&nbsp;hoặc&nbsp;<strong>writeFile</strong>.</p>

<p style="text-align: justify;">Khi tương tác với hệ thống file, bạn luôn dùng các phương thức bất đồng bộ để duy trì bản chất không chặn của lặp sự kiện và cải thiện hiệu suất và phản hồi của ứng dụng.</p>

<p style="text-align: justify;">Tuy nhiên, các phương thức đồng bộ có vai trò riêng của chúng trong những trường hợp nhất định, đặc biệt là khi bạn đang viết các tập lệnh đơn giản hoặc xử lý những thao tác tệp 1 lần.</p>

<h2 style="text-align: justify;">Đọc file JSON với mô đun fs</h2>

<p style="text-align: justify;">Để đọc file JSON, đầu tiên, nhập mô đun fs bất đồng bộ vào file chính như sau:</p>

<pre id="pre0">
<code>const fs = require(&quot;node:fs/promises&quot;);</code></pre>

<p style="text-align: justify;">Nếu đang dùng phiên bản thấp hơn Node.js 18, nhập mô đun&nbsp;<strong>fs</strong>&nbsp;như sau:</p>

<pre id="pre1">
<code>const fs = require(&quot;fs/promises&quot;);</code></pre>

<p style="text-align: justify;">Bạn có thể đọc file JSON bằng phương thức<strong>&nbsp;readFile</strong>&nbsp;nhận 2 đối số: một đường dẫn file và một đối tượng cấu hình tùy chọn. Đối số config xác định các lựa chọn để đọc file và có thể là một đối tượng với những lựa chọn hay mã hóa chuỗi.</p>

<p style="text-align: justify;">Tùy chọn đối tượng bao gồm:</p>

<ul>
	<li style="text-align: justify;"><strong>Encoding</strong>&nbsp;(string, mặc định là utf8): Lựa chọn này xác định ký tự mã hóa để dùng khi đọc file. Những mã hóa thông dụng bao gồm “utf8” cho file văn bản và “binary” cho file nhị phân.</li>
	<li style="text-align: justify;"><strong>Flag&nbsp;</strong>(string, mặc định là r): Lựa chọn này xác định flag hệ thống file được dùng khi mở tập tin. Những flag thông dụng bao gồm “r” cho việc đọc, và “w” cho việc viết.</li>
</ul>

<p style="text-align: justify;">Ví dụ:</p>

<pre id="pre2">
<code>fs.readFile(&quot;./users.json&quot;, { encoding: &quot;utf-8&quot;, flag: &quot;r&quot; })
  .then((data) =&gt; {
    const users = JSON.parse(data);
    console.log(users);
  })
  .catch((error) =&gt; {
    console.error(&#039;Error reading the JSON file:&#039;, error);
  });</code></pre>

<div style="text-align: justify;"><iframe allowtransparency="true" data-google-container-id="a!3" data-google-query-id="CJ7eu_P9ooIDFXHPTAIdoEkGAw" data-load-complete="true" frameborder="0" height="0" hspace="0" id="aswift_2" marginheight="0" marginwidth="0" name="aswift_2" sandbox="" scrolling="no" vspace="0" width="694"></iframe></div>

<p style="text-align: justify;">Code này đọc một file JSON tên&nbsp;<strong>users.json</strong>&nbsp;trong thư mục hiện tại. Khi bạn truy xuất dữ liệu của file, bạn có thể phân tích nó từ JSON vào đối tượng JavaScript bằng&nbsp;<strong>JSON.parse</strong>. Điều này cho phép bạn truy cập và chỉnh sửa dữ liệu dưới dạng một đối tượng trong code.</p>

<h2 style="text-align: justify;">Ghi file JSON bằng mô đun fs</h2>

<p style="text-align: justify;">Bạn có thể viết dữ liệu vào file JSON bằng phương thức&nbsp;<strong>writeFile</strong>. Phương pháp này tính 3 đối số:</p>

<ul>
	<li style="text-align: justify;">Một đường dẫn file.</li>
	<li style="text-align: justify;">Dữ liệu bạn muốn ghi vào file. Nó có thể là một chuỗi, một buffer, một AsyncIterable, hoặc một đối tượng Iterable.</li>
	<li style="text-align: justify;">Một đối tượng cấu hình tùy chọn.</li>
</ul>

<p style="text-align: justify;">Phương thích này ghi dữ liệu không đồng bộ vào một file. Nếu file tồn tại, nó ghi đè nội dung hiện có vào nội dung mới. Nếu file không tồn tại, nó tạo tập tin, rồi điền dữ liệu bạn chuyển dưới dạng đối số vào nó.</p>

<p style="text-align: justify;">Ví dụ:</p>

<pre id="pre3">
<code>const fakeUsers = &#91;
  {
    id: 1,
    name: &quot;John Doe&quot;,
    username: &quot;johndoe123&quot;,
    address: {
      street: &quot;123 Main St&quot;,
      city: &quot;Anytown&quot;,
    },
  },
  {
    id: 2,
    name: &quot;Jane Smith&quot;,
    username: &quot;janesmith456&quot;,
    address: {
      street: &quot;456 Elm St&quot;,
      city: &quot;Another City&quot;,
    },
  }
&#93;;

fs.writeFile(&quot;./users.json&quot;, JSON.stringify(fakeUsers), {
  encoding: &quot;utf-8&quot;,
  flag: &quot;w&quot;,
}).catch((error) =&gt; {
  console.error(&#039;Error writing the JSON file:&#039;, error);
});</code></pre>

<p style="text-align: justify;">Dữ liệu bạn chuyển vào hàm writeFile phải là một chuỗi hoặc vùng đệm, vì thế, nếu bạn muốn ghi một đối tượng vào file, đầu tiên, bạn phải chuyển đổi nó sang dạng chuỗi bằng phương thức&nbsp;<strong>JSON.stringify</strong>.</p>

<h2 style="text-align: justify;">Update file JSON bằng mô đun fs</h2>

<p style="text-align: justify;">Mô đun<strong>&nbsp;fs</strong>&nbsp;không cung cấp cách rõ ràng để update file, vì việc ghi tệp sẽ đè lên dữ liệu hiện tại.</p>

<p style="text-align: justify;">Để xử lý vấn đề này, trước tiên bạn có thể update file bằng cách lấy nội dung hiện tại từ file bằng phương thức&nbsp;<strong>readFile</strong>. Sau đó, thêm dữ liệu hiện có vào dữ liệu hiện tại và chuyển nó đi dưới dạng đối số dữ liệu trong phương thức&nbsp;<strong>writeFile</strong>.</p>

<p style="text-align: justify;">Đây là một hàm triển khai logic trên:</p>

<pre id="pre4">
<code>const updateFile = async (filePath, data) =&gt; {
  try {
    const fileContents = await fs.readFile(filePath, {
      encoding: &quot;utf-8&quot;,
      flag: &quot;r&quot;,
    });

    const fileData = JSON.parse(fileContents);

    const updatedFileData = &#91;...fileData, ...data&#93;;

    await fs.writeFile(filePath, JSON.stringify(updatedFileData), {
      encoding: &quot;utf-8&quot;,
      flag: &quot;w&quot;,
    });

    return &quot;File updated successfully&quot;;
  } catch (error) {
    console.error(&#039;Error updating the JSON file:&#039;, error);
  }
};</code></pre>

<p style="text-align: justify;">Bạn có thể gọi hàm như sau:</p>

<pre id="pre5">
<code>updateFile(&quot;./users.json&quot;, &#91;
  {
    id: 4,
    name: &quot;Jane Doe&quot;,
    username: &quot;janedoe123&quot;,
    address: {
      street: &quot;123 Main St&quot;,
      city: &quot;Anytown&quot;,
    },
  },
  {
    id: 5,
    name: &quot;John Smith&quot;,
    username: &quot;johnsmith456&quot;,
    address: {
      street: &quot;456 Elm St&quot;,
      city: &quot;Another City&quot;,
    },
  }
&#93;).then((message) =&gt; {
  console.log(message);
});</code></pre>

<div style="text-align: justify;"><iframe allowtransparency="true" data-google-container-id="a!4" data-google-query-id="CNW5qv79ooIDFcQHKgodZP8EIA" data-load-complete="true" frameborder="0" height="0" hspace="0" id="aswift_3" marginheight="0" marginwidth="0" name="aswift_3" sandbox="" scrolling="no" vspace="0" width="694"></iframe></div>

<p style="text-align: justify;">Khối code này sẽ thêm người dùng kèm thông tin ở trên vào file&nbsp;<strong>users.json</strong>&nbsp;hiện tại.</p>

<p style="text-align: justify;">Bảo vệ ứng dụng Node.js khi đọc và ghi file JSON liên quan tới các vấn đề bảo mật quan trọng. Bạn nên xác thực dữ liệu JSON thường xuyên để đảm bảo nó hoạt động đúng như mong đợi. Bạn cũng nên hạn chế quyền truy cập và tẩy xóa dữ liệu đầu vào của người dùng để ngăn chặn nguy cơ hổng dữ liệu.</p>
		</div>
				<div id="author">
						<p>
				<strong>Nguồn tin:</strong>
				Quantrimang.com
			</p>
		</div>
	</div>
	<div id="footer" class="clearfix">
		<div id="url">
			<strong>URL của bản tin này: </strong><a href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/cach-doc-va-ghi-file-json-trong-node-js-7713.html" title="Cách đọc và ghi file JSON trong Node.js">https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/cach-doc-va-ghi-file-json-trong-node-js-7713.html</a>

		</div>
		<div class="clear"></div>
		<div class="copyright">
			&copy; .&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.
		</div>
		<div id="contact">
			<a href="mailto:admin@nguoicodonvn2008.info">admin@nguoicodonvn2008.info</a>
		</div>
	</div>
</div>
        <div id="timeoutsess" class="chromeframe">
            Bạn đã không sử dụng Site, <a onclick="timeoutsesscancel();" href="https://www.nguoicodonvn2008.info/#">Bấm vào đây để duy trì trạng thái đăng nhập</a>. Thời gian chờ: <span id="secField"> 60 </span> giây
        </div>
        <div id="openidResult" class="nv-alert" style="display:none"></div>
        <div id="openidBt" data-result="" data-redirect=""></div>
		</script>
		<div class="car-top">
  <span><img src="https://www.nguoicodonvn2008.info/themes/default/images/car.png" alt=""></span>
</div>
<script src="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js"></script>
<script>var nv_base_siteurl="/",nv_lang_data="vi",nv_lang_interface="vi",nv_name_variable="nv",nv_fc_variable="op",nv_lang_variable="language",nv_module_name="news",nv_func_name="savefile",nv_is_user=0, nv_my_ofs=-4,nv_my_abbr="EDT",nv_cookie_prefix="nv4c_e856T",nv_check_pass_mstime=1738000,nv_area_admin=0,nv_safemode=0,theme_responsive=0,nv_recaptcha_ver=2,nv_recaptcha_sitekey="",nv_recaptcha_type="image",XSSsanitize=1;</script>
<script src="https://www.nguoicodonvn2008.info/assets/js/language/vi.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/global.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/site.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/news.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/main.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/custom.js"></script>
<script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "Organization",
            "url": "https://www.nguoicodonvn2008.info",
            "logo": "https://www.nguoicodonvn2008.info/uploads/angel.gif"
        }
        </script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js"></script>
<script type="text/javascript">
var $scrolltop = $('.car-top');
$scrolltop.on('click', function () {
    $('html,body').animate({
        scrollTop: 0
    }, 800);
    $(this).addClass("car-run");
    setTimeout(function(){ $scrolltop.removeClass('car-run');}, 1000);
    return false;
});
$(window).on('scroll', function ()
{ 
    if($(window).scrollTop() >= 200)
    {
        $scrolltop.addClass("show");
        $scrolltop.addClass("car-down");
    }
    else
    {
       $scrolltop.removeClass("show");
       setTimeout(function(){ $scrolltop.removeClass('car-down');}, 300);
    }
});
</script>
</body>
</html>