---
title: "Node.js中文乱码解决"
author: "coolwhy1"
date: "2015-10-26T16:18:27Z"
tags: []
categories: ["Web前端"]
slug: "node-js"
draft: false
lastmod: "2015-10-26T16:18:38Z"
id: 2252000
url: "https://coolwhy1.iteye.com/blog/2252000"
---

> 使用NodeJS，当有中文时，如果不做任何处理就会出现乱码。因为，NodeJS 不支持 GBK。当然，UTF-8是支持的。

所以，要确保不出现乱码，应做到以下两点：

- 保证你的 JS文件是以UTF-8格式保存的。
- 在你的JS文件中的 writeHead 方法中加入 "charset=utf-8" 编码，如下例所示：
  
  ```
    var http = require("http");
  
    http.createServer(function (req, res) {
        res.writeHead(200, {
            "Content-Type": "text/html;charset=utf-8"
        });
  
        res.end("<h1>你好</h1>");
    }).listen(3000);
  ```