It is a so-called arrow function. It is a short form for defining function expressions. Hence,
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
is basically similar to:
fs.writeFile('message.txt', 'Hello Node.js', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
Anyway, there is big difference bitween the syntaxes: While function
creates a new scope for this
, an arrow function re-uses the outer scope. Hence, in a callback defined using the function
keyword you may need something such as
const that = this;
to preserve the outer scope, using an arrow function you don't need that. Please note that this also means that you are not able to use bind
with an arrow function (i.e., it's not possible to redefine this
for an arrow function (okay, to be true, you can use it, but the first parameter won't have any effect)).
Apart from that, please note that you can omit the parentheses around the parameter if there is only one. Hence, instead of
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
you may also write:
fs.writeFile('message.txt', 'Hello Node.js', err => {
if (err) throw err;
console.log('It\'s saved!');
});
Anyway, this only works if there is only one parameter.