Node.js uygulamaları, NPM paket kayıt defterinde bulunan bir milyondan fazla açık kaynak paketinden yararlanır. En popüler paketler haftalık 10 milyonun üzerinde indirme alır ve küçük evcil hayvan projelerinden tanınmış teknoloji girişimlerine kadar birçok uygulamanın temelinde yer alır. Bugün modern web uygulamalarındaki kodun yüzde 97'si npm modüllerinden geliyor.
Sizi tekerleği yeniden icat etmekten kurtaracak popüler olanlara kısaca değineceğiz.
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
const fastify = require('fastify')({
logger: true
});
fastify.get('/', async (request, reply) => {
reply.type('application/json').code(200);
return { hello: 'world' };
});
fastify.listen(3000, (err, address) => {
if (err) throw err;
fastify.log.info(`App listening on ${address}`);
});
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('event', data => { /* … */ });
client.on('disconnect', () => { /* … */ });
});
server.listen(3000);
const async = require("async");
async.mapLimit(urls, 5, async function(url) {
const response = await fetch(url);
return response.body;
}, (err, results) => {
if (err) throw err;
// results is now an array of the response bodies
console.log(results);
});
const { range } = require('rxjs');
const { map, filter } = require('rxjs/operators');
range(1, 200).pipe(
filter(x => x % 2 === 1),
map(x => x + x)
).subscribe(x => console.log(x));
const _ = require("lodash");
const nums = _.range(1, 9);
// => [1, 2, 3, 4, 5, 6, 7, 8, 9]
const chunks = _.chunk(nums, 3);
// => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const right = _.takeRight(nums, 2);
// => [7, 8, 9]
const _ = require(“underscore);
const list = [[5, 1, 7], [3, 2, 1]];
_.invoke(list, 'sort');
// => [[1, 5, 7], [1, 2, 3]]
import * as R from 'ramda';
const double = x => x * 2;
R.map(double, [1, 2, 3]);
// => [2, 4, 6]
R.map(double, {x: 1, y: 2, z: 3});
// => {x: 2, y: 4, z: 6}
var validator = require('validator');
validator.isEmail('foo@bar.com'); //=> true
import * as yup from 'yup';
let schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required().positive().integer(),
email: yup.string().email(),
website: yup.string().url(),
createdOn: yup.date().default(function () {
return new Date();
}),
});
// check validity
schema
.isValid({
name: 'jimmy',
age: 24,
})
.then(valid =>
console.log(valid) // => true
);
// you can try and type cast objects to the defined schema
schema.cast({
name: 'jimmy',
age: '24',
createdOn: '2014-09-23T19:25:25Z',
});
// => { name: 'jimmy', age: 24, createdOn: Date }
const dayjs = require(“dayjs”);
dayjs().startOf('month').add(1, 'day').set('year', 2018).format('YYYY-MM-DD HH:mm:ss');
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
format(new Date(), '[Today is a] dddd')
//=> "Today is a Wednesday"
formatDistance(subDays(new Date(), 3), new Date())
//=> "3 days ago"
formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
const jwt = require('jsonwebtoken');
const token = jwt.sign({ foo: 'bar' }, 'shhhhh');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
const { v4: uuidv4 } = require('uuid');
uuidv4(); // => '1a68a438-b077-468b-b1e8-dcdd976a0f5b'
const fs = require(‘fs-extra’);
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile');
console.log('success!');
} catch (err) {
console.error(err);
}
}
copyFiles();
const rimraf = require(“rimraf”);
rimraf('./build', error => {
if (error) console.error(error);
});
const mkdirp = require('mkdirp')
// return value is a Promise resolving to the first directory created
mkdirp('/tmp/foo/bar/baz').then(made =>
console.log(`made directories, starting with ${made}`));
const glob = require("glob");
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
});
const shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}