Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

node.js: FYI about the readFileSync encoding

EDIT: Would love to know how to get this post associated w/ the video, but I'm only given JavaScript as an option for the topic

In the node.js video 'Binding Values', we are instructed to set the encoding option for the readFileSync like this:

var fileContents = fs.readFileSync('./views/' + templateName + '.html', {endcoding: 'utf8'});

But that does not work.

After digging into the Node documentation I found this is the way to write it:

var fileContents = fs.readFileSync('./views/' + templateName + '.html', 'utf8');

1 Answer

They're both valid syntax under node.js v0.10.40 and any version thereafter.

var fs = require('fs')

var file = fs.readFileSync('testfile.txt', {encoding: 'utf8'});
console.log(file);

var alternateFile = fs.readFileSync('testfile.txt', 'utf8');
console.log(alternateFile);

Here's the Typescript definition for the two versions of the function:

/*
     * Synchronous readFile - Synchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param encoding
     */
    export function readFileSync(filename: string, encoding: string): string;
    /*
     * Synchronous readFile - Synchronously reads the entire contents of a file.
     *
     * @param fileName
     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.
     */
    export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;

Thanks, yes I figured they were probably both valid. But the current workspaces setup does not work with the example given in the video. So this was just a heads up to anyone who runs into the same problem I did with getting it to work.