node.js -- 檔案輸出入

JavaScript

簡介

歷史

開發工具

基本語法

運算式

分枝

迴圈

函數

陣列

物件導向

原型

封裝

繼承

多型

this

控制流程

進階功能

Eval 函數

Closure

JSONP

小書籤

字串

正規表達式

除錯方法

伺服端

播 midi

cookie

套件

ccc函式庫

2D 繪圖

3D 繪圖

影像處理

訊號處理

語音處理

數學計算

tex 數學式

格式轉換

桌面應用

自然語言

地理資訊

平台

Node.js

jQuery

Google

numeric.js

Titanium

引擎

語法

作品

翻譯精靈

繪圖精靈

DotWiki

流程

前端工程師

後端工程師

css

訊息

相關網站

參考文獻

最新修改

簡體版

English

讀取檔案

程式:readfile.js

var fs = require("fs"),
    filename = "index.html",
    encode = "utf8";

fs.readFile(filename, encode, function(err, file) {
  console.log(file);
});

輸入檔:index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-7" />
    <title>node.js index html file</title>
</head>
<body>
    <h1>node.js index html file</h1>
</body>
</html>

執行結果

D:\ccc101\nodejs>node readfile.js
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-7" />
    <title>node.js index html file</title>
</head>
<body>
    <h1>node.js index html file</h1>
</body>
</html>

寫入檔案 — writefile1.js

var fs = require('fs');
fs.writeFile("writefile1.txt", "Hello!\noutput file\nby Node.js", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

寫入檔案 — writefile2.js

var fs = require('fs');
fs.writeFile("writefile1.txt", "Hello!\noutput file\nby Node.js", function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

參考文獻

  1. node.js 檔案讀取 — http://book.nodejs.tw/zh-tw/node_basic.html#id2
  2. http://stackoverflow.com/questions/2496710/nodejs-write-to-file

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License