Script to convert Node libraries to Deno

nodedeno

Script to convert Node libraries to Deno

  • Transform CJS to ESM
  • Transform TypeScript to JavaScript
  • Any dependency is replaced with ./deps.js
  • Replace some Node global object like process.env or __dirname to Deno equivalents

Example:

const dep = require("my-dependency");
const otherModule = require("./other-module");

module.exports = function foo() {};
module.exports.otherModule = function bar() {};

Is converted to:

import dep from "./deps.js";
import otherModule from "./other-module.js";

export default function foo() {};
export const otherModule = function bar() {};

Usage:

import { convert } from "https://raw.githubusercontent.com/oscarotero/nodedeno/main/mod.js"

convert({
  from: "node-library/lib",
  to: "deno-library/lib",
  depsFile: "deps.js",
  ignoredFiles: [
    "ignored-file-1.js",
    "ignored-file-2.js",
  ],
  modules: {
    "module-name": "./new-module.js"
  },
  onConvert(file, code) {
    // Here you can make additional changes to the code or filename
    return [file, code];
  }
})

Options

  • from The directory of the source files
  • to The destination of the converted files
  • depsFile The dependencies file that will be copied in the destination folder (and renamed to deps.js
  • ignoredFiles An array of files that won’t be copied
  • onConvert A callback that will be invoked for every file copied. It allows to make additional changes
  • modules An object to customize some modules resolution.
  • transpile Set true to convert TypeScript files to Javascript.

Used in

Download Details:

Author: oscarotero

Source Code: https://github.com/oscarotero/nodedeno

#deno #node #nodejs #javascript

What is GEEK

Buddha Community

Script to convert Node libraries to Deno

joseph Garrone

1605735944

Well done!
I love the idea if gathering all the dependencies in a single deps.ts file it’s verry neat.

Have you heard about Denoify?
You are of course wellcome if you want to join forces with me :)

denoify

Script to convert Node libraries to Deno

nodedeno

Script to convert Node libraries to Deno

  • Transform CJS to ESM
  • Transform TypeScript to JavaScript
  • Any dependency is replaced with ./deps.js
  • Replace some Node global object like process.env or __dirname to Deno equivalents

Example:

const dep = require("my-dependency");
const otherModule = require("./other-module");

module.exports = function foo() {};
module.exports.otherModule = function bar() {};

Is converted to:

import dep from "./deps.js";
import otherModule from "./other-module.js";

export default function foo() {};
export const otherModule = function bar() {};

Usage:

import { convert } from "https://raw.githubusercontent.com/oscarotero/nodedeno/main/mod.js"

convert({
  from: "node-library/lib",
  to: "deno-library/lib",
  depsFile: "deps.js",
  ignoredFiles: [
    "ignored-file-1.js",
    "ignored-file-2.js",
  ],
  modules: {
    "module-name": "./new-module.js"
  },
  onConvert(file, code) {
    // Here you can make additional changes to the code or filename
    return [file, code];
  }
})

Options

  • from The directory of the source files
  • to The destination of the converted files
  • depsFile The dependencies file that will be copied in the destination folder (and renamed to deps.js
  • ignoredFiles An array of files that won’t be copied
  • onConvert A callback that will be invoked for every file copied. It allows to make additional changes
  • modules An object to customize some modules resolution.
  • transpile Set true to convert TypeScript files to Javascript.

Used in

Download Details:

Author: oscarotero

Source Code: https://github.com/oscarotero/nodedeno

#deno #node #nodejs #javascript

Akshara Singh

Akshara Singh

1622015491

Bitcoin Exchange script | Cryptocurrency Exchange Script | Free Live Demo @ Coinsclone

Hey peeps, Hope you all are safe & going well

Many entrepreneurs & startups are interested to start a crypto exchange platform by using a cryptocurrency exchange script, you know why??? Let me explain. Before that, you need to know what is a cryptocurrency exchange script???

What is Cryptocurrency Exchange Script???

Cryptocurrency Exchange Script is an upgrade version of all exchange platforms, it is also called ready-made script or software. By using the crypto exchange script you can launch your crypto trading platform instantly. It is one of the easiest and fastest ways to start your crypto exchange business. Also, it helps to launch your exchange platform within 7 days.

Benefits of Bitcoin Exchange Script:

  • Customizing options - They will help you to build your cryptocurrency exchange platform based on your business needs.
  • Monitor and Engage - You can easily monitor the work process
  • Beta module - You can test your exchange in the Beta module
  • Cost-effective - The development will be around $8k - $15k (It may be vary based on the requirement)
  • Time-Period - You can launch your exchange within 1 week

Best Trading & Security Features of Bitcoin Exchange Script:

  • Multi-language
  • IEO launchpad,
  • Crypto wallet,
  • Instant buying/selling cryptocurrencies
  • Staking and lending
  • Live trading charts with margin trading API and futures 125x trading
  • Stop limit order and stop-loss orders
  • Limit maker orders
  • Multi-cryptocurrencies Support
  • Referral options
  • Admin panel
  • Perpetual swaps
  • Advanced UI/UX
  • Security Features [HTTPs authentication, Biometric authentication, Jail login, Data encryption, Two-factor authentication, SQL injection prevention, Anti Denial of Service(DoS), Cross-Site Request Forgery(CSRF) protection, Server-Side Request Forgery(SSRF) protection, Escrow services, Anti Distributed Denial of Service]

The More Important one is “Where to get the best bitcoin exchange script?”

Where to get the best bitcoin exchange script?

No one couldn’t answer the question directly because a lot of software/script providers are available in the crypto market. Among them, finding the best script provider is not an easy task. You don’t worry about that. I will help you. I did some technical inspection to find the best bitcoin exchange script provider in the techie world. Speaking of which, one software provider, Coinsclone got my attention. They have successfully delivered 100+ secured bitcoin exchanges, wallets & payment gateways to their global clients. No doubt that their exchange software is 100% bug-free and it is tightly secured. They consider customer satisfaction as their priority and they are always ready to customize your exchange based on your desired business needs.

Of course, it kindles your business interest; but before leaping, you can check their free live demo at Bitcoin Exchange Script.

Are you interested in business with them, then connect their business experts directly via

Whatsapp/Telegram: +919500575285

Mail: hello@coinsclone.com

Skype: live:hello_20214

#bitcoin exchange script #cryptocurrency exchange script #crypto exchange script #bitcoin exchange script #bitcoin exchange clone script #crypto exchange clone script

HYIP Investment Script: Twisted It with Crowdfunding & Lending Platform - Benefits Of It!

Are you wanting to be an Entrepreneur? A Business using cryptocurrency? Then this article is for you.

As a beginner, always one prefers fair play. But to the least, initiating business in the streams of cryptocurrency carries a varying degree of risks. We all know that, Every business packs the profit only if we are ready to take risks. But flabbergast is, you can avoid unnecessary risk, If you choose our Twisted HYIP Investment script. You don’t need to play poker with your hard-earned Money.

Using minimal investment, You can start a beneficial business.

Craze for cryptocurrency is now seeming to be unlimited, Using the Twisted HYIP platform you will get funds for running the lending business- this is the one line of the process.

This is image title

First, let me make plain, How our traditional HYIP works?

You can create a number of investment plans with attractive and promising Rate of interest. Investors will invest in those plans and get their interest periodically.

How you will provide them interest? You have to collect the investments and use them for your own project, Trading, Stock marketing and so on.

What if you don’t find a right platform to grow your investor’s funds. You will lack in processing their interest, and it will be filthy, right?

How it works?

So this Twisted HYIP platform clear this shady cloud and brings you the best place to grow your investors’ funds. With our platform you can run Investment as well as lending platform together. You will run a traditional HYIP script for your investors stating the fixed Rate of interest with validity for processing their principle back.

Instead of using the crowded funds in different platform, You can use it for lending to borrowers in your platform at an interest rate higher than promised to your investors. Now you can pay back the investors as well as you will get a constant flow of income for you.

This is image title

Instead of generating promised interest rate daily or monthly, You can also make it as a doubler with long term duration. So you can use the investors fund as well as lenders repay again and again.

Every investor can monitor their investment growth in their dashboard. They will get back their invested amount plus additional ROI only when their investment gets matures. But they can see, how their wallet is loaded with profits without any risk.

Possibility of being a Profitable business

  1. Cryptocurrencies are now obligatory assets. We can predict it as future currency, which sweep away the paper currency. An anxiousness to earn more Cryptocurrency with minimal investment, attracts more people.
  2. Everyone will have a dream to achieve. They will be loaded with talents, but lack of funds. You can be a lender with handsome interest.
  3. Not only for Cryptos, You can use the same script for fiats and live ERC20 tokens. So there are many doors to knock. If one shuts you kick the other.
  4. You can use a single script as Stacking for Erc20, HYIP with promised returns, lending with an affordable rate of interest and also as a Doubler.

Crucial bits of Twisted HYIP

  • Easy to Navigate and Highly informative Admin dashboard
  • Continuous growth monitors with a wide range of opportunities in Investor Dashboard
  • Affordable deals with more information loaded Borrower Dashboard
  • Third party integrated AML/KYC Security segments
  • Multiple cryptocurrency supportable payment methods
  • Useful Affiliate system and level bonuses.
  • Highly customizable
  • Perform multiple script

Cryptocurrency market is blooming one, as per the voices of many financial expertise, prediction for end of digital currency is a blue moon. This twisted HYIP will create its own market as a perception for profit is getting increased every day among the people.

Now are you ready to launch your own lending platform? then Connect with KIR HYIP to know more interesting features about the platform. There is always space to add your ideas.

Under a short span of time, launch your own turnkey based lending platform. The World is running behind Profit, what are you waiting for? Join the club now and get the free HYIP software demo!

#hyip script #hyip investment script #bitcoin hyip script #buy hyip script #best hyip script #hyip investment script

How to Convert Base 2 Binary Number String To integer In Python

In this pythonn tutorial we will learn about how to convert base 2 binary number string to integer in Python. Ever faced the challenge of converting a binary number string into an integer for smooth processing in your Python code? Python offers seamless solutions for transforming data types without a hitch, making it an ideal choice for developers worldwide.

In this article, we’ll delve into two popular methods to tackle binary string conversion: Python’s built-in int() function and the powerful bitstring library, part of the bit array package. Join us as we break down each approach, guiding you through the process of efficient typecasting in Python.

What Is A Base-2 Number String?

A binary number is expressed in the base-2 number system using only “0”s and “1”s. The zeros and ones are called the index of a binary number. They are also called “bits”.

A computer system only uses the binary system for computations. It is the way in which machine code is written. Circuit diagrams can be used to represent the working of binary systems.

Boolean algebra including “AND”, “OR” and “NOT” gates can be used to represent addition, subtraction, multiplications in the binary system.

We can easily convert a number that is an integer from the decimal system, that is the base-10 system to the binary system by dividing it with 2 and arranging the remainders in a bottom-to-top order.

From Decimal To Base 2 Conversion

Converting Decimal to Base-2 Numbers

A binary number can also be converted easily into a decimal number in mathematics.

CONVERTING A BASE 2 NUMBER TO AN INTEGER

Converting a Base-2 Number String to an Integer in Python

A string in python is something that is written between two quotation marks, for example, “this is a string”.

Hence, a base-2 number string is a binary number written between two quotation marks . For example-‘1010001’ is a base-2 number string.

Advantages of Explicit Typecasting in Python

In python, programmers can clearly define the conversion of one data type into another in their code. This is known as explicit typecasting in python.

Explicit typecasting is extremely useful. Unlike other programming languages, python has built-in functions that can perform explicit typecasting without having to write huge blocks of code for transforming one data type into another.

Explicit typecasting has many advantages. Some of them are:

  • It helps in converting lower data types into higher ones for ease of operations.
  • It prevents the loss of data when converting from one data type to another.
  • Functions like int() and str() are extremely helpful and hassle free to use.

Method 1: Converting Base-2 Number String to Integer Using int() Function

We can use the int() built-in function to convert a string literal into an integer in python. Let’s look at how we can implement this :

#converting a base-2 number string into an integer.
#taking an input for a number in the form of a string
inin=input("Enter a binary number= ")
#displaying the input
print("The given input is=",inin)
#converting using int()
outout=int(inin,2)
#displaying the output
print("the number in the decimal system or as an integer is=",outout)

The output would be:

Enter a binary number= 10011
The given input is= 10011
the number in the decimal system or as an integer is= 19

Using The Int Function

Example: Converting Binary String with int() Function

Method 2: Converting Base-2 Number String to Integer Using BitString Library

The bitstring module helps in natural and easy creation of binary data. Binary data analysis and manipulation using bitstring comes in very handy along with the BitArray class.

Before we can use this module we have to install in it our system, run the following code in your command prompt:

pip install bitstring

Let’s see how we can implement this:

#converting a base-2 number string into an integer.
#importing required modules
from bitstring import BitArray
#taking an input for a number in the form of a string
inin=input("Enter a binary number= ")
#displaying the input
print("The given input is=",inin)
#converting using bitArray
outout=BitArray(bin=inin).int
#displaying the output
print("the number in the decimal system or as an integer is=",outout)

The output will be:

Enter a binary number= 0100111
The given input is= 0100111
the number in the decimal system or as an integer is= 39

Using The Bitstring Module

Example: Converting Binary String with Bitstring Module

Conclusion

Throughout this tutorial, we’ve explored the process of converting binary numbers to decimal integers in Python. With Python’s extensive library of built-in functions and modules, there’s no need for manual calculations. Explicit typecasting is a powerful feature that simplifies this conversion process. We have demonstrated two methods for converting base-2 number strings to integers: using the int() function and the bitstring module.

Article source at: https://www.askpython.com

#python 

Connor Mills

Connor Mills

1653964894

Deno vs Node.js | Converting an Existing Node.js Module to Deno

A general purpose methodology for converting a Node.js package to Deno.

Deno is a new runtime for JavaScript that supports TypeScript natively without the need for compilation. It was created by Ryan Dahl, the creator of Node.js, to solve some of Node’s fundamental design and security flaws and embrace modern best practices like ES Modules and TypeScript.

At EdgeDB, we built and maintain a first-party client library for Node.js that’s available as the edgedb module on NPM. However, Deno uses a totally different set of practices to handle dependencies, namely direct URL imports from public package registries like deno.land/x. We set out to find a simple way to “Denoify” our codebase; that is, generate a Deno-compatible module from our existing Node.js implementation with minimal refactoring. This frees us from the complexity of maintaining and synchronizing two nearly identical codebases.

We landed on a “runtime adapter” pattern that we think represents a general-purpose approach that may be useful to other library authors looking to support Deno.

Node.js vs Deno​

There are a few key differences between the Node.js and Deno runtimes that we will have to take into account when adapting our library written for Node.js:

TypeScript support: Deno can directly execute TypeScript files, while Node.js can only run JavaScript code.

Module resolution: By default, Node.js imports modules in the CommonJS format and expects require/module.exports syntax. It also has a complex resolution algorithm, which will load plain module names like "react" from node_modules, append .js or .json as needed to extensionless imports, and import the index.js file if the import path is a directory.

Deno simplifies this dramatically. It uses the ECMAScript module syntax import and export, also known as “ES modules” or just “ESM”. This syntax is also used by TypeScript. All imports must be either a) a relative path with an explicit file extensions or b) a URL.

This means there is no node_modules or package manager like npm or yarn; external modules are simply imported directly via a URL from a publicly available code repository, like deno.land/x or GitHub.

Standard library: Node.js has a builtin set of standard modules like fs, path, crypto, and http, among others. These modules can be directly required with require('fs') and their names are reserved by Node.js. By contrast, the Deno standard library is imported via URL from the https://deno.land/std/ registry. The functionality of the two standard libraries also differs, with Deno abandoning some old or outdated Node.js APIs, introducing a new standard library (inspired by that of Go), and uniformly supporting modern JavaScript features like Promises (whereas many Node.js APIs still rely on the older callback style).

Built-in globals: Deno contains all of its core APIs under a single global variable called Deno and otherwise only exposes standard web APIs. Unlike Node.js, there is no global Buffer or process variable available.

So how can we work around these differences and get our Node.js library running in Deno as painlessly as possible? Let’s go through these changes one by one.

TypeScript and module syntax​

Fortunately, we don’t need to worry much about converting CommonJS require/module.exports syntax to ESM import/export. We wrote edgedb-js entirely in TypeScript, which already uses ESM syntax. During compilation, tsc converts our files to plain JavaScript files utilizing CommonJS require syntax. The compiled files are directly consumable by Node.js.

The rest of this post will discuss how we modify our TypeScript source files to a format that is directly consumable by Deno.

Dependencies​

Fortunately edgedb-js doesn’t have any third-party dependencies, so we don’t have to worry about the Deno compatibility of any external libraries. However, we need to replace all imports from the Node.js standard library (e.g. path, fs, etc) with a Deno equivalent.

If your package does depend on external packages, check deno.land/x to see if a Deno version if available. If so, read on; if not, you’ll need to work with the module author to make a Deno version available.

This task is made far simpler by the existence of the Node.js compatibility module provided by the Deno standard library. This module provides a wrapper over Deno’s standard library that attempts to adhere as faithfully as possible to Node’s API.

import * as crypto from "crypto";
import * as crypto from "https://deno.land/std@0.114.0/node/crypto.ts";

To simplify things, we moved all imports of Node.js APIs to a single file called adapter.node.ts and re-export only the functionality we need.

// adapter.node.ts
import * as path from "path";
import * as util from "util";
import * as crypto from "crypto";

export {path, net, crypto};

We then implement the same adapter for Deno in a file called adapter.deno.ts.

// adapter.deno.ts
import * as crypto from "https://deno.land/std@0.114.0/node/crypto.ts";
import path from "https://deno.land/std@0.114.0/node/path.ts";
import util from "https://deno.land/std@0.114.0/node/util.ts";

export {path, util, crypto};

Whenever we need Node.js specific functionality, we import it from adapter.node.ts directly. This way, we can make edgedb-js Deno-compatible by simply rewriting all imports of adapter.node.ts to adapter.deno.ts. As long as these files re-export the same functionality, everything should work as expected.

Practically speaking, how do we actually rewrite these imports? Well, we need to write a simple codemod script. And just to make it a bit more poetic, we’ll write this script using Deno itself.

Writing a Deno-ifier​

Before we get started building, let’s outline what steps this tool needs to do:

Rewrite the Node.js-style imports to the more explicit style Deno. This includes adding the .ts file extension and adding /index.ts to all directory imports.

Swapping out all imports from adapter.node to adapter.deno.ts.

Inject Node.js globals like process and Buffer into the Deno-ified code. While we could simply export these variables from our adapters, we’d have to refactor our Node.js files to explicitly import them. To simplify things, we’ll detect where Node.js globals are used and inject an import as needed.

Rename the src directory to _src to denote that it holds the internals of edgedb-js and shouldn’t be imported directly

Move the main src/index.node.ts file to the project root and rename it mod.ts. This is idiomatic in Deno. (Note: the naming of index.node.ts here doesn’t indicate that it’s Node-specific; it’s indented to differentiate it from index.browser.ts, which exports all browser-compatible parts of edgedb-js.)

Create a list of all files​

Let’s jump in. First, we need to compute a list of our source files. The walk function provided by Deno’s native fs module will do:

import {walk} from "https://deno.land/std@0.114.0/fs/mod.ts";

const sourceDir = "./src";
for await (const entry of walk(sourceDir, {includeDirs: false})) {
  // iterate through all files
}

Note that we’re using Deno’s native std/fs module, not the Node compatibility version std/node/fs.

Let’s declare a set of rewrite rules and initialize a Map that will map from a source file path to the rewritten destination path.

const sourceDir = "./src";
const destDir = "./edgedb-deno";
const pathRewriteRules = [
  {match: /^src\/index.node.ts$/, replace: "mod.ts"},
  {match: /^src\//, replace: "_src/"},
];

const sourceFilePathMap = new Map<string, string>();

for await (const entry of walk(sourceDir, {includeDirs: false})) {
  const sourcePath = entry.path;
  sourceFilePathMap.set(sourcePath, resolveDestPath(sourcePath));
}

function resolveDestPath(sourcePath: string) {
  let destPath = sourcePath;
  // apply all rewrite rules
  for (const rule of pathRewriteRules) {
    destPath = destPath.replace(rule.match, rule.replace);
  }
  return join(destDir, destPath);
}

That’s the easy part; now lets start modifying the source code itself.

Rewrite imports and exports​

To rewrite the import paths, we need to know where they are in the file; fortunately TypeScript exposes its Compiler API, which we’ll use to parse the source files into an abstract syntax tree (AST) and find the import declarations.

To do so, we need to import the compiler API directly from the "typescript" NPM module. Fortunately, Deno’s compatibility module provides a way to require CommonJS modules without much hassle. This does require the use of the --unstable flag when running Deno, but for a build step like this, it’s not a problem.

import {createRequire} from "https://deno.land/std@0.114.0/node/module.ts";

const require = createRequire(import.meta.url);
const ts = require("typescript");

Let’s iterate through the files and parse each one in turn.

import {walk, ensureDir} from "https://deno.land/std@0.114.0/fs/mod.ts";
import {createRequire} from "https://deno.land/std@0.114.0/node/module.ts";

const require = createRequire(import.meta.url);
const ts = require("typescript");

for (const [sourcePath, destPath] of sourceFilePathMap) {
  compileFileForDeno(sourcePath, destPath);
}

async function compileFileForDeno(sourcePath: string, destPath: string) {
  const file = await Deno.readTextFile(sourcePath);
  await ensureDir(dirname(destPath));

  // if file ends with '.deno.ts', copy the file unchanged
  if (destPath.endsWith(".deno.ts")) return Deno.writeTextFile(destPath, file);
  // if file ends with '.node.ts', skip file
  if (destPath.endsWith(".node.ts")) return;

  // parse the source file using the typescript Compiler API
  const parsedSource = ts.createSourceFile(
    basename(sourcePath),
    file,
    ts.ScriptTarget.Latest,
    false,
    ts.ScriptKind.TS
  );
}

For each parsed AST, let’s iterate through its top-level nodes to find import and export declarations. We don’t need to look deeper, because import/export are always top-level statements (with the exception of dynamic import(), but we don’t use those in edgedb-js).

From these nodes, we extract the start and end offsets of the import/export path in the source file. We can then rewrite the import by slicing out the current contents and inserting a modified path.

const parsedSource = ts.createSourceFile(/*...*/);

const rewrittenFile: string[] = [];
let cursor = 0;
parsedSource.forEachChild((node: any) => {
  if (
    (node.kind === ts.SyntaxKind.ImportDeclaration ||
      node.kind === ts.SyntaxKind.ExportDeclaration) &&
    node.moduleSpecifier
  ) {
    const pos = node.moduleSpecifier.pos + 2;
    const end = node.moduleSpecifier.end - 1;
    const importPath = file.slice(pos, end);

    rewrittenFile.push(file.slice(cursor, pos));
    cursor = end;

    // replace the adapter import with Deno version
    let resolvedImportPath = resolveImportPath(importPath, sourcePath);
    if (resolvedImportPath.endsWith("/adapter.node.ts")) {
      resolvedImportPath = resolvedImportPath.replace(
        "/adapter.node.ts",
        "/adapter.deno.ts"
      );
    }

    rewrittenFile.push(resolvedImportPath);
  }
});

rewrittenFile.push(file.slice(cursor));

The key part here is the resolveImportPath function, which converts a Node-style local import to the Deno style through trial-and-error. First it checks if the path corresponds to an actual file on disk; it that fails, it tries appending .ts; if that fails, it tries appending /index.ts; if that fails, an error is thrown.

Inject Node.js globals​

The final step is to handle the Node.js globals. First, we create a globals.deno.ts file in our project directory. This file should export the compatibility versions of all Node.js globals that are used in your package.

export {Buffer} from "https://deno.land/std@0.114.0/node/buffer.ts";
export {process} from "https://deno.land/std@0.114.0/node/process.ts";

The compiled AST helpfully provides a Set of all identifiers used in the source file. We’ll use that to inject an import statement in any file that references these globals.

const sourceDir = "./src";
const destDir = "./edgedb-deno";
const pathRewriteRules = [
  {match: /^src\/index.node.ts$/, replace: "mod.ts"},
  {match: /^src\//, replace: "_src/"},
];
const injectImports = {
  imports: ["Buffer", "process"],
  from: "src/globals.deno.ts",
};

// ...

const rewrittenFile: string[] = [];
let cursor = 0;
let isFirstNode = true;
parsedSource.forEachChild((node: any) => {
  if (isFirstNode) {  // only run once per file
    isFirstNode = false;

    const neededImports = injectImports.imports.filter((importName) =>
      parsedSource.identifiers?.has(importName)
    );

    if (neededImports.length) {
      const imports = neededImports.join(", ");
      const importPath = resolveImportPath(
        relative(dirname(sourcePath), injectImports.from),
        sourcePath
      );
      const importDecl = `import {${imports}} from "${importPath}";\n\n`;

      const injectPos = node.getLeadingTriviaWidth?.(parsedSource) ?? node.pos;
      rewrittenFile.push(file.slice(cursor, injectPos));
      rewrittenFile.push(importDecl);
      cursor = injectPos;
    }
  }

Writing the files​

Finally, we’re ready to write the rewritten source file to its new home in the destination directory. First, we delete any existing contents, then write each file in turn.

try {
  await Deno.remove(destDir, {recursive: true});
} catch {}

const sourceFilePathMap = new Map<string, string>();
for (const [sourcePath, destPath] of sourceFilePathMap) {
  // rewrite file
  await Deno.writeTextFile(destPath, rewrittenFile.join(""));
}

Continuous integration​

A common pattern is to maintain a separate auto-generated repo for the Deno version of your package. In our case, we generate the Deno version of edgedb-js inside GitHub Actions whenever a new commit is merged into master. The generated files are then published to a sister repository called edgedb-deno. Below is a simplified version of our workflow file.

# .github/workflows/deno-release.yml
name: Deno Release
on:
  push:
    branches:
      - master
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout edgedb-js
        uses: actions/checkout@v2
      - name: Checkout edgedb-deno
        uses: actions/checkout@v2
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          repository: edgedb/edgedb-deno
          path: edgedb-deno
      - uses: actions/setup-node@v2
      - uses: denoland/setup-deno@v1
      - name: Install deps
        run: yarn install
      - name: Get version from package.json
        id: package-version
        uses: martinbeentjes/npm-get-version-action@v1.1.0
      - name: Write version to file
        run: echo "${{ steps.package-version.outputs.current-version}}" > edgedb-deno/version.txt
      - name: Compile for Deno
        run: deno run --unstable --allow-env --allow-read --allow-write tools/compileForDeno.ts
      - name: Push to edgedb-deno
        run: cd edgedb-deno && git add . -f && git commit -m "Build from $GITHUB_SHA" && git push

An additional workflow inside edgedb-deno then creates a GitHub release, which publishes a new version to deno.land/x. That’s left as an exercise for the reader, though you can use our workflow as a starting point.

Wrapping up​

This is a broadly generalizable pattern for converting an existing Node.js module to Deno. Refer to the edgedb-js repo for the full Deno compilation script, cross- workflow.

Original article source at https://www.edgedb.com

#deno #node #javascript #programming