惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
The road to universal JavaScript
2022-05-09 · via oida.dev | TypeScript, Rust

Universal JavaScript. JavaScript that works in every environment. JavaScript that runs on both the client and the server, something thinking about for years (see 1, 2). Where are we now?

A little example #

Let’s say I need to parse the titles from 100 podcast episodes. They’re in some old XML format that is a bit tough to parse. What do I need to write this in modern-day Node.js?

import { XMLParser } from "fast-xml-parser";
import { url_prefix } from "./data.mjs";

function fetch_episode(episode_number) {
return fetch(`${url_prefix}${episode_number}`)
.then(res => res.text())
.then(data => {
const obj = new XMLParser().parse(data)
return obj['!doctype'].html.head.meta.meta.title
})
.catch((e) => {
return undefined
})
}

const episode_requests = new Array(100)
.fill(0)
.map((el, i) => fetch_episode(i))

const results = await Promise.all(episode_requests)

// List all of them
console.log(results.filter(Boolean))

Okay, that’s not bad. fast-xml-parser is a Node.js dependency. Since the Node.js team spent some time getting modules up and running, I can use this CommonJS style module in an EcmaScript module. Just like that.

$ npm install --save fast-xml-parser

Loading resources via fetch is available in Node 18 without a flag. You can test it in earlier versions using --experimental-fetch. There are some edge cases that might require some attention, but overall it’s in a good shape and it’s fun to use. Fantastic work, Node, and Undici teams!

What about Deno? #

There are more JavaScript runtimes out there. What about Deno? This is my main script:

import { XMLParser } from "fast-xml-parser";
import { url_prefix } from "./data.mjs";

function fetch_episode(episode_number) {
return fetch(`${url_prefix}${episode_number}`)
.then(res => res.text())
.then(data => {
const obj = new XMLParser().parse(data)
return obj['!doctype'].html.head.meta.meta.title
})
.catch((e) => {
return undefined
})
}

const episode_requests = new Array(100)
.fill(0)
.map((el, i) => fetch_episode(i))

const results = await Promise.all(episode_requests)

// List all of them
console.log(results.filter(Boolean))

Wait? That’s the same script? Does it work just like that?

Not exactly. Deno uses a different way to load modules: It requires them via pointing to a URL. Tools like Skypack and JSPM allow Node.js dependencies to be delivered via URL. And a nice feature called Import Maps make it nice to wire them up in your code.

{
"imports": {
"fast-xml-parser": "https://ga.jspm.io/npm:[email protected]/src/fxp.js"
},
"scopes": {
"https://ga.jspm.io/": {
"strnum": "https://ga.jspm.io/npm:[email protected]/strnum.js"
}
}
}

There is an import map generator that lives on the JSPM site. The same output can be used to make the same script work in the browser (CORS issues notwithstanding).

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>The website's title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script type="importmap">
{
"imports": {
"fast-xml-parser": "https://ga.jspm.io/npm:[email protected]/src/fxp.js"
},
"scopes": {
"https://ga.jspm.io/": {
"strnum": "https://ga.jspm.io/npm:[email protected]/strnum.js"
}
}
}
</script>

<script type="module">
// .. see above
</script>
</body>
</html>

But isn’ that cool? Since the fast-xml-parser has no native dependencies, just JavaScript, it works out of the box.

Cloudflare workers #

Okay, there are more JavaScript runtimes out there. One JS runtime that I use a lot are Cloudflare workers. They’re edge handlers and allow for quick transformations of responses before you deliver. I can use – you guessed it – the same script as above. I deal with dependencies by bundling them up with esbuild

$ esbuild index.mjs --bundle --outfile=bundle.js --format=esm

I also limit the number of titles to fetch by 10. Cloudflare workers are for edge responses, they need to limit the outgoing connections for tons of reasons.

On my own JavaScript runtime #

I currently work on a JavaScript runtime. It’s based on Rust and Deno and deals with a couple of intricacies that are unique to the domain I’m operating in. Early on we decided to focus on web standards and support fetch, EcmaScript modules, etc. to make sure we have a common subset of compatibility. Guess what. The script above works just like that on my own JavaScript runtime.

Winter #

I think having the possibility to run the same code everywhere is exciting, and it’s also a wonderful step in the right direction. It’s a start, and there’s a lot more to achieve in the future. But the future looks bright.

Today, folks at Cloudflare, Deno, Vercel, Node.js, Bloomberg, and Shopify have announced the Web Interoperable JavaScript Community Group, or in short: wintercg. This group wants to ensure that all runtime vendors move in the same direction by adopting features that are available in browsers as a common standard.

Also, check out James Snell’s talk “Yes, Node.js is part of the web platform”, which should give you more ideas about where everything is heading.

For me, it’s great! Choosing web standards has made my effort compatible with all the other vendors. What does this mean for you? Cross-platform compatible dependencies. You chose the platform that works best for your need, and you can take your app along.

Related Articles