const yaml = require('js-yaml');
const fs = require('fs');
// Get document, or throw exception on error
try {
const doc = yaml.load(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
console.log(doc);
} catch (e) {
console.log(e);
}
interface User {
name: string;
id: number;
}
const user: User = {
name: "Hayes",
id: 0,
};
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
// Write all logs with level `error` and below to `error.log`
new winston.transports.File({ filename: 'error.log', level: 'error' }),
// Write all logs with level `info` and below to `combined.log`
new winston.transports.File({ filename: 'combined.log' }),
],
});
logger.log({
level: 'error',
message: 'Hello distributed log files!'
});
logger.info('Hello again distributed logs');
const debug = require('debug')('http')
, http = require('http')
, name = 'My App';
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}
nodemon ./server.js
.env
dosyadan bir dosyaya yükleyen sıfır bağımlılıklı bir modüldür .process.env
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
require('dotenv').config();
const db = require('db');
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
});
{
"scripts": {
"start-prod": "cross-env NODE_ENV=production node ./app.js"
}
}
const { program } = require('commander');
program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');
program.parse(process.argv);
const options = program.opts();
if (options.debug) console.log(options);
console.log('pizza details:');
if (options.small) console.log('- small pizza size');
if (options.pizzaType) console.log(`- ${options.pizzaType}`);
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const argv = yargs(hideBin(process.argv)).argv;
if (argv.ships > 3 && argv.distance < 53.5) {
console.log('Plunder more riffiwobbles!');
} else {
console.log('Retreat from the xupptumblers!');
}
const argv = require('minimist')(process.argv.slice(2));
console.log(argv);
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
const colors = require('colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red) // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow
console.log('Run the trap'.trap); // Drops the bass
const ora = require('ora');
const spinner = ora('Loading unicorns').start();
setTimeout(() => {
spinner.color = 'yellow';
spinner.text = 'Loading rainbows';
}, 1000);
const { DynamoDBClient, ListTablesCommand } = require("@aws-sdk/client-dynamodb");
(async () => {
const client = new DynamoDBClient({ region: "us-west-2" });
const command = new ListTablesCommand({});
try {
const results = await client.send(command);
console.log(results.TableNames.join("\n"));
} catch (err) {
console.error(err);
}
})();
const axios = require('axios');
async function getUser() {
try {
const response = await axios.get('/user', { params: { ID: 12345 } });
console.log(response);
} catch (error) {
console.error(error);
}
}
getUser();
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
const nodemailer = require("nodemailer");
async function main() {
const testAccount = await nodemailer.createTestAccount();
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user, // generated ethereal user
pass: testAccount.pass, // generated ethereal password
},
});
await transporter.sendMail({
from: '"Fred Foo ????" <foo@example.com>', // sender address
to: "bar@example.com, baz@example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});
}
main().catch(console.error);
const mongoose = require(“mongoose”);
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const BlogPost = new Schema({
author: ObjectId,
title: String,
body: String,
date: Date
});
Her iyi Node.js geliştiricisi, en popüler NPM paketlerine aşina olmalıdır.
Bir kod parçası yazmadan önce, bir iş sorununu çözüyor musunuz yoksa özel durumunuzun o kadar benzersiz olup olmadığını düşünmeye çalışın. Kayıt defterindeki açık kaynak kodunun miktarıyla, birinin bunun için zaten bir paket oluşturmuş olma olasılığı yüksektir. Onu aramak her zaman çabaya değer.
İnsanlar her gün binlerce paketi NPM'ye gönderir ve hepsi sağlam değildir. Uygulamanızın bağımlılıklarına dikkat etmelisiniz. Kanıtlanmış bir sicile, yüksek haftalık indirmelere, yakın zamanda taahhüt geçmişine, birim testlerine, GitHub yıldızlarına ve birkaç katkıda bulunanlara sahip paketler genellikle güvenli bir bahistir.
Ancak üçüncü taraf koduyla her zaman 0 emin olamazsınız.