Node.js在fs的模組提供了檔案的讀取、寫入、重新命名、刪除、檢查目錄

fs的模組中都提供了非同步的和同步的兩個版本,例:讀取檔案內容
Fs.readFile(filename, [encoding],[callback(err,dtta)]) //非同步
Fs.readFileSync() //同步

Fs.readFile參數說明:

    Filename-檔名; encoding-字元編碼; callback-回呼函數
    Callback提供了兩個參數;err表示有沒有錯誤;data表示檔案內容

同步與非同步的差異在於同步方式會以函數傳回值的形式傳回內容

以下範例操作了新增檔案並寫入’Hello World’、讀取檔案、新增第二行’Hello World2’、再次讀取檔案和最後將檔案刪除

Node.js

//fs.js

//write file
var fs = require('fs');

fs.writeFile('./hello.txt', 'Hello World')

//read file
fs.readFile('./hello.txt', 'utf-8', function(err, data) {
    if (err) {
      console.err(err);
    } else {
      console.log(data);
      }
});

//append file
fs.appendFile('./hello.txt', '\nHello World 2', function (err) {
});

fs.readFile('./hello.txt', 'utf-8', function(err,data) {
    console.log(data)
});

//delete file
fs.unlink('./hello.txt')

Python

#fs.py

#write file
fs = open('./hello.txt', 'w')
print >> fs, 'Hello World\n'
fs.close

#read file
fs = open('./hello.txt', 'r')
print fs.read()
fs.close

#append file
fs = open('./hello.txt', 'a')
fs.write('Hello World2')
fs.close

#read file
fs = open('./hello.txt', 'r')
for line in fs:
    print line
fs.close

#delete file
import os
os.remove('./hello.txt')
arrow
arrow
    文章標籤
    node.js python
    全站熱搜

    長風破浪會有時 發表在 痞客邦 留言(0) 人氣()