var arr = ['Foo', 'Bar']
console.log(`Olá
${arr[0]}
e
${arr[1]}`)
var studios = [
'20th Century Fox',
'Warner Bros.',
'Walt Disney Pictues'
]
var lengths = studios.map( s => s.length)
console.log(lengths)
console.log('1');
t();
console.log('3');
function t() {
console.log('2');
}
console.log('1');
t();
console.log('3');
function t() {
setTimeout(() => {
console.log('2');
}, 10);
}
let http = require('http');
let server = http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
if(request.url === '/') {
response.end('Hello World\n');
} else if(request.url === '/contato') {
response.end('[email protected]\n');
} else {
response.end('Not found');
}
});
server.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
// new Promise(function(resolve, reject) {
//
// });
// const wait = time => new Promise(resolve => setTimeout(resolve, time));
//
// wait(1000).then(() => console.log('Hello!'));
const wait = function(time) {
return new Promise(function(resolve) {
return setTimeout(resolve, time)
});
};
// wait(2000)
// .then(() => console.log( 'Foo BAR' ))
wait(2000)
// onFulfilled() can return a new promise `x`
.then(() => new Promise(res => res('foo')))
// the next promise will assume the state of `x`
.then(a => a)
// Above we returned the unwrapped value of `x`
// so `.then()` above returns a fulfilled promise
// with that value:
.then(b => console.log(b)) // 'Foo'
// Note that `null` is a valid promise value:
.then(() => null)
.then(c => console.log(c)) // null
// The following error is not reported yet:
.then(() => {throw new Error('foo');})
// Instead, the returned promise is rejected
// with the error as the reason:
.then(
// Nothing is logged here due to the error above:
d => console.log(`d: ${ d }`),
// Now we handle the error (rejection reason)
e => console.log(e)
) // [Error: foo]
// Wiith the previous exceptions handled, we can continue:
.then(f => console.log(`f: ${ f }`)) // f: undefined
// The following doesn't log. e was already handled.
// so this handler doesn't get called:
.catch(e => console.log(e))
.then(() => { throw new Error('bar'); })
// When a promise is rejected, success handlers get skipped.
// Nothing logs here because of the 'bar' exception:
.then(g => console.log(`g: ${ g }`))
.catch(h => console.log(h)) // [Error: bar]
var noTry = false ? 'do' : 'do not';
console.log(noTry);
var noTry2 = false || 'do nottt'
console.log(noTry2);
BattleDroid.prototype = Object.create(Droid.prototype);
const net = require('net');
const server = net.createServer((socket) => {
socket.end('goodbye\n');
}).on('error', (err) => {
// handle errors here
throw err;
});
// grab an arbitrary unused port.
server.listen(() => {
console.log('opened server on', server.address());
});
#!/usr/bin/env node
/**
* loremipsum.js
*
* Faz uma requisiçâo na API `http://loripsum.net/api/`
* e grava um arquivo com o nome e quantidade
* de parágrafos espificados
*
* William Bruno, Maio de 2015
*/
var http = require('http');
var fs = require('fs');
var fileName = String(process.argv[2] || '').replace(/[^a-z0-9\.]/gi, '');
var quantityOfParagraphs = String(process.argv[3] || '').replace(/[^\d]/g, '');
const USAGE = 'Uso: node loremipsum.js {nomeArquivo} {quantidadeParágrafos}';
if (!fileName || !quantityOfParagraphs) {
return console.log(USAGE);
}
http.get(`http://loripsum.net/api/${quantityOfParagraphs}`, function(res){
var text = '';
res.on('data', function(chunk) {
text += chunk;
});
res.on('end', function() {
fs.writeFile(fileName, text, function() {
console.log(`Arquivo ${fileName} pronto`);
});
});
}).on('error', function(e) {
console.log('Got error: ' + e.message);
});
var arr = ['Foo', 'Bar'],
i = 0,
max = arr.length;
while (i < max) {
console.log( arr[i] );
i++;
}
var arr = ['Foo', 'Bar'];
arr.map(function(x) {
console.log(x);
});
var arr = ['Foo', 'Bar'];
for (var i = 0, max = arr.length; i < max; i++) {
console.log(arr[i]);
}
process.stdout.write('Han Solo\n');
// process.argv.forEach(function(arg) {
// console.log(arg);
// });
// for(arg of process.argv) {
// console.log(arg);
// }
// process.argv.map(arg => console.log(arg))
console.log(process.argv);
var arr = ['Foo', 'Bar'];
for(x of arr){
console.log(x);
}
for(x in arr){
console.log(x);
}
// converte o valor pra seu booleano
console.log( !!'' );
console.log( !!'foo' );
console.log( !!0 );
console.log( !!1 );
/*
var bye = function(str1) {
return function(str2) {
return `${str1} ${str2}`;
}
};
var good = bye('Good');
var greet = good('Bye');
console.log(greet);
*/
function currier(fn) {
var args = Array.prototype.slice.call(arguments, 1);
// console.log(args);
// console.log(arguments);
return function() {
console.log(arguments);
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments, 0)));
}
}
var bye = function(str1, str2) {
return `${str1} ${str2}`;
};
var good = currier(bye, 'Good');
console.log(
good('Bye!')
);
// 'use-strict'
//
// let net = require('net')
// let chatServer = net.createServer()
// let clientList = []
//
// let removeClient = () => client.splice(client.indexOf(5), 1)
// let broadcast = () => {
// for(var i = clientList.length -1; i >= 0; i-- ) {
// if(client !== client[i]) {
// clientList[i].write(message)
// }
// }
// }
//
// chatServer.on('connection', client => {
// client.write(`Hi guest !\n`)
// clientList.push(client)
// client.on('data', data => {
// console.log(data, client)
// })
// client.on('error', err => {
// console.log(err);
// })
// client.on('end', removeClient)
// })
//
// chatServer.listen(9000)
'use strict';
const net = require('net');
const chatServer = net.createServer();
const clientList = [];
let broadcast = function (message, client) {
for (let i = clientList.length - 1; i >= 0; i--) {
if (client !== clientList[i]) {
clientList[i].write(message);
}
}
};
chatServer.on('connection', function (client) {
client.write('Hi guest' + '!\n');
clientList.push(client);
client.on('data', function (data) {
broadcast(data, client);
});
client.on('end', function () {
console.log('client', clientList.indexOf(client));
clientList.splice(clientList.indexOf(client), 1);
});
client.on('error', function(err) {
console.log(err);
});
});
chatServer.listen(9000);
var arr = ['Foo', 'Bar'];
arr.map(function(x) {
console.log(this);
});
design pattern Observer Syntatic sugar heraça classica
livro: principios de orientacao a objetos em js
JS tem seis tipos primitivos String Number Boolean Null Undefined Symbol
Douglas Crockford: Javascript: A menos ententida lingaguem de programacao do globo
programacao funcional
publicar module no npm
REPL - console do node js
Array.reduce
node inspector
editorConfig.org
hoisting
funcoes sao objetos de primeira classe
IIFE
nodejs --v8-options|grep 'harmony'
Singleton
pagina 26 ha um erro arr ou invez de max
promises - promisesaplus.com Promise, Promise.all()
template string - interpolar variaveis
chmod +x loremipsum.js
how to deal with debug module and env vars
https://nodejs.org/api/net.html
DAO - data access ObjectId
orm
Squelize
waterline
mongosse
dbs with nodejs: oracledb, mysql, sqlserver, redis
express generator
exec()
json web tokens
salt (decodificacao)