TNTWeb – The full name of Tencent News Zhongtai front-end team, partners in the group have practiced and accumulated experience in Web front-end, NodeJS development, UI design, mobile APP and other large front-end fields.
At present, the team mainly supports the front-end development of Tencent news business. Besides business development, some front-end infrastructure has been accumulated to enable business efficiency improvement and product innovation.
The team advocates open source construction, has a variety of technical masters, the team Github address: github.com/tnfe
Yunfeng Github: github.com/ihtml5
Software engineers have long sought to speed up the development process by reducing code duplication in programs. The Nodejs ecosystem reuses code in the form of NPM packages, with more than 1 million open source packages currently available. NPM packages are used by everyone from small Internet projects to big-name tech startups. Some of the most popular packages are downloaded by tens of millions of people every week and form the basis for many applications. Today, much of the code in modern Web applications comes from NPM modules. We’ve rounded up 30 common NodeJS installers to save you from reinventing the wheel.
First, practical functions
1. qs
An easy to use string parsing and formatting library
const qs = require('qs');
constv assert = require('assert');
const obj = qs.parse('a=c');
assert.deepEqual(obj, { a: 'c' });
const str = qs.stringify(obj);
assert.equal(str, 'a=c');
Copy the code
2.rxjs
RxJS is a set of modular libraries for composing asynchronous and event-based programs using observable collections and combinations in JavaScript.
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));
Copy the code
3. mitt
Micro 200b function event emitter/publish subscription.
import mitt from 'mitt'
const emitter = mitt()
emitter.on('foo'.e= > console.log('foo', e) )
emitter.on(The '*'.(type, e) = > console.log(type, e) )
emitter.emit('foo', { a: 'b' })
emitter.all.clear()
function onFoo() {}
emitter.on('foo', onFoo) // listen
emitter.off('foo', onFoo) // unlisten
Copy the code
4.Underscore.js
Underscore. Js is a utility tape library for JavaScript that provides support for the usual suspects of functionality (each, Map, Reduce, filter, and so on) without extending any of the core JavaScript objects.
const _ = requireThe underscore (");const list = [[5.1.7], [3.2.1]];
_.invoke(list, 'sort');
// => [[1, 5, 7], [1, 2, 3]]
Copy the code
5.day.js
Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers, and has an API that is largely compatible with Moment.
const dayjs = require(" dayjs "); dayjs().startOf('month').add(1.'day').set('year'.2018).format('YYYY-MM-DD HH:mm:ss');
Copy the code
6.Ramda
Ramda is a useful functional library with no side effects functions that can be combined with Kerrization.
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}
Copy the code
7.validator
Validator is a library of string validators and cleaners.
var validator = require('validator');
validator.isEmail('[email protected]'); //=> true
Copy the code
8.yup
Yup is a schema builder for complex, interdependent validation and transformation.
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(a); })});// 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 }
Copy the code
9.Lodash
Lodash is a utility library that makes JavaScript easier by eliminating the hassle of handling arrays, numbers, objects, strings, and more.
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]
Copy the code
10.date-fns
Date-fns provides the most comprehensive, simple, and consistent set of tools for manipulating JavaScript dates in browsers and Node.js.
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."
Copy the code
11.jsonwebtoken
Jsonwebtoken is a library for signing, validating, and decoding JSON Web tokens.
const jwt = require('jsonwebtoken');
const token = jwt.sign({ foo: 'bar' }, 'shhhhh');
Copy the code
12.uuid
UUID is a library used to create RFC4122 universal unique identifiers.
const { v4: uuidv4 } = require('uuid');
uuidv4(); // => '1a68a438-b077-468b-b1e8-dcdd976a0f5b'
Copy the code
2. Operate the file system
1.rimraf
Rimraf provides nodes with the UNIX equivalent of the rm -rf command.
const rimraf = require(" rimraf "); rimraf('./build'.error= > {
if (error) console.error(error);
});
Copy the code
2.fs-extra
Fs-extra adds file system methods not included in the native FS module and promise support for FS methods.
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();
Copy the code
3.mkdirp
Just like mkdir -p, mkdirp recursively creates directories and all necessary subdirectories.
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}`));
Copy the code
4.glob
Glob is a library that uses multiple pattern matching files.
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.
});
Copy the code
5.shelljs
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands based on the Node.js API.
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);
}
Copy the code
6.js-yaml
Js-yaml is an implementation of YAML, a popular humanized data serialization language.
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);
}
Copy the code
Third, Web framework
1. koa
Koa is a new Web framework designed by the team behind Express to be a smaller, more expressive, and more robust foundation for Web applications and apis.
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Copy the code
2. express
Express is is the most popular, fastest, and minimalist Node.js backend Web framework.
const express = require('express');
const app = express();
app.get('/'.function (req, res) {
res.send('Hello World');
});
app.listen(3000);
Copy the code
3. Fastify
Fastify is one of the fastest extensible Web frameworks out there, focused on providing the best developer experience with minimal overhead.
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}`);
});
Copy the code
4. socket.io
Socket.IO enables real-time bidirectional event-based communication using long polling or WebSockets, with disconnection detection and automatic reconnection support.
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);
Copy the code
Iv. Auxiliary development
1. jest
Jest is complete and ready to set up the JavaScript test solution
test('adds 1 + 2 to equal 3'.() = > {
expect(1 + 2).toBe(3);
});
Copy the code
2. typescript
TypeScript is extensible JavaScript. It is a language that adds optional types and compiles them into plain readable JavaScript.
interface User {
name: string;
id: number;
}
const user: User = {
name: "Hayes".id: 0};Copy the code
3.winston
Winston is a simple and generic logging library that supports multiple transports.
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');
Copy the code
4.debug
Debug is a miniature JavaScript debugging utility that mimics the debugging techniques at the core of Node.js.
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');
});
Copy the code
5. eslint
ESLint is a tool for finding and fixing problems in JavaScript and TypeScript code.
{
"rules": {
"semi": ["error"."always"]."quotes": ["error"."double"]}}Copy the code
6. nodemon
Nodemon is a tool that helps develop Node.js-based applications by automatically restarting node applications when it detects file changes in the directory.
nodemon ./server.js
Copy the code
7. dotenv
Dotenv is a zero-dependency module that loads environment variables from.env files into process.env
.env file:
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
});
Copy the code
8. cross-env
Cross-env enables scripts to set and use environment variables across platforms.
{
"scripts": {
"start-prod": "cross-env NODE_ENV=production node ./app.js"}}Copy the code