zoukankan      html  css  js  c++  java
  • 【nodejs】 文件系统(fs) 之读写文件


    //
    写入文件 var data = "hello world"; fs.writeFile('c:\a.txt', data, 'ascii', function(err) { if (err) { console.log('写入文件失败'); } else { console.log('保存成功, 赶紧去看看乱码吧'); } }); //读取文件 fs.readFile('c:\a.txt', 'ascii', function(err, data) { if (err) { console.log('写入文件失败'); } else { console.log(data); } }); //[注意:默认情况下,数据编码为utf8;mode=438 ;flag=w]

    如果有中文呢?

    由于Node.js仅支持如下编码:utf8, ucs2, ascii, binary, base64, hex,并不支持中文GBK或GB2312之类的编码,

    因此如果要读写GBK或GB2312格式的文件的中文内容,必须要用额外的模块:iconv-lite

     

    1、安装模块:npm install iconv-lite

    windows平台不支持npm  先解决这个问题

    Microsoft Windows [版本 6.1.7601]
    版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

    C:Windowssystem32>node -v
    v0.12.5

    C:Windowssystem32>npm -v
    2.11.2

    C:Windowssystem32>

    ok  成功!

    =========================

    加载的文件必须是GB2312格式的

    var iconv = require('iconv-lite');
    var fs = require("fs") ;
    fs.readFile("c:\v.txt",function (error,data){
    if(error){throw error} ;
    var str = iconv.decode(data, 'GB2312'); 
    console.log(str);
    }) ;

    utf-8的文件如下

     var fs = require("fs") ;
     fs.readFile("bb.txt","utf8",function (error,data){
         if(error) throw error ;
         console.log(data) ;
     }) ;
  • 相关阅读:
    ureport2 数据源配置
    ureport2 + spring boot 搭建
    alibaba
    Maven Helper
    在Idea中连接数据库并生成实体类
    Intellij jrebel 热部署 安装
    IDEA使用说明
    JPA 常用注解 (hibernate)
    vue + canvas 图片加水印
    vue——批量下载图片
  • 原文地址:https://www.cnblogs.com/viewcozy/p/4611330.html
Copyright © 2011-2022 走看看