Polyglot CheatSheet - IO

Updated: 2018-05-30

Read File

Node

Read file, fs.readFile will read file as binary

var data = fs.readFileSync("data.json");
console.log(data);
//<Buffer 7b 22 32 30 30 30 22 3a 5b 7b 22 52 61 6e 6b 22 3a 31 2c 22 41 69 72 70 6f 72 74 22 3a 22 20 48 61 72 74 73 66 69 65 6c 64 2d 4a 61 63 6b 73 6f 6e 20 41 ...>

Use .toString() to get String

var str = fs.readFileSync("data.txt").toString();

Use JSON.parse() to get JSON

var data = JSON.parse(fs.readFileSync("data.json"));

Python

with open('filepath') as f:
    lines = f.read()

This will read all the lines at once, and may cause memory issue for large files.

To read and process the file line by line:

for line in open(path):
    do_something(line)

Write File

Node

Write file, use JSON.stringify()

fs.writeFile("filename.json", JSON.stringify(data));

List Files

Python

Returning a list of file names:

>>> import os
>>> os.listdir(path)
['foo.txt', 'bar.txt']