Code Monkey home page Code Monkey logo

package-template's Introduction

napi-rs

This project was initialized from xray

A framework for building compiled Node.js add-ons in Rust via Node-API. Website: https://napi.rs

chat Stake to support us

Platform Support

Test & Release FreeBSD Address Sanitizer Memory Leak Detect

MSRV

Rust 1.65.0

node12 node14 node16 node18 node20
Windows x64
Windows x86
Windows arm64
macOS x64
macOS aarch64
Linux x64 gnu
Linux x64 musl
Linux aarch64 gnu
Linux aarch64 musl
Linux arm gnueabihf
Linux arm muslebihf
Linux powerpc64le gnu
Linux s390x gnu
Linux riscv64 gnu N/A N/A
Linux aarch64 android
Linux armv7 android
FreeBSD x64

This library depends on Node-API and requires [email protected] or later.

We already have some packages written by napi-rs: node-rs

One nice feature is that this crate allows you to build add-ons purely with the Rust/JavaScript toolchain and without involving node-gyp.

Taste

You can start from package-template to play with napi-rs

Define JavaScript functions

/// import the preludes
use napi::bindgen_prelude::*;
use napi_derive::napi;

/// module registration is done by the runtime, no need to explicitly do it now.
#[napi]
fn fibonacci(n: u32) -> u32 {
  match n {
    1 | 2 => 1,
    _ => fibonacci(n - 1) + fibonacci(n - 2),
  }
}

/// use `Fn`, `FnMut` or `FnOnce` traits to defined JavaScript callbacks
/// the return type of callbacks can only be `Result`.
#[napi]
fn get_cwd<T: Fn(String) -> Result<()>>(callback: T) {
  callback(env::current_dir().unwrap().to_string_lossy().to_string()).unwrap();
}

/// or, define the callback signature in where clause
#[napi]
fn test_callback<T>(callback: T)
where T: Fn(String) -> Result<()>
{}

/// async fn, require `async` feature enabled.
/// [dependencies]
/// napi = {version="2", features=["async"]}
#[napi]
async fn read_file_async(path: String) -> Result<Buffer> {
  tokio::fs::read(path)
    .map(|r| match r {
      Ok(content) => Ok(content.into()),
      Err(e) => Err(Error::new(
        Status::GenericFailure,
        format!("failed to read file, {}", e),
      )),
    })
    .await
}

more examples at examples

Building

This repository is a Cargo crate. Any napi-based add-on should contain Cargo.toml to make it a Cargo crate.

In your Cargo.toml you need to set the crate-type to "cdylib" so that cargo builds a C-style shared library that can be dynamically loaded by the Node executable. You'll also need to add this crate as a dependency.

[package]
name = "awesome"

[lib]
crate-type = ["cdylib"]

[dependencies]
napi = "3"
napi-derive = "3"

[build-dependencies]
napi-build = "1"

And create build.rs in your own project:

// build.rs
extern crate napi_build;

fn main() {
  napi_build::setup();
}

So far, the napi build script has only been tested on macOS Linux Windows x64 MSVC and FreeBSD.

Install the @napi-rs/cli to help you build your Rust codes and copy Dynamic lib file to .node file in case you can require it in your program.

{
  "package": "awesome-package",
  "devDependencies": {
    "@napi-rs/cli": "^1.0.0"
  },
  "napi": {
    "name": "jarvis" // <----------- Config the name of native addon, or the napi command will use the name of `Cargo.toml` for the binary file name.
  },
  "scripts": {
    "build": "napi build --release",
    "build:debug": "napi build"
  }
}

Then you can require your native binding:

require('./jarvis.node')

The module_name would be your package name in your Cargo.toml.

xxx => ./xxx.node

xxx-yyy => ./xxx_yyy.node

You can also copy Dynamic lib file to an appointed location:

napi build [--release] ./dll
napi build [--release] ./artifacts

There are documents which contains more details about the @napi-rs/cli usage.

Testing

Because libraries that depend on this crate must be loaded into a Node executable in order to resolve symbols, all tests are written in JavaScript in the test_module subdirectory.

To run tests:

yarn build:test
yarn test

Related projects

Features table

Rust Type Node Type NAPI Version Minimal Node version Enable by napi feature
u32 Number 1 v8.0.0
i32/i64 Number 1 v8.0.0
f64 Number 1 v8.0.0
bool Boolean 1 v8.0.0
String/&'a str String 1 v8.0.0
Latin1String String 1 v8.0.0 latin1
UTF16String String 1 v8.0.0
Object Object 1 v8.0.0
serde_json::Map Object 1 v8.0.0 serde-json
serde_json::Value any 1 v8.0.0 serde-json
Array Array 1 v8.0.0
Vec Array 1 v8.0.0
Buffer Buffer 1 v8.0.0
External External 1 v8.0.0
Null null 1 v8.0.0
Undefined/() undefined 1 v8.0.0
Result<()> Error 1 v8.0.0
T: Fn(...) -> Result Function 1 v8.0.0
Async/Future Promise 4 v10.6.0 async
AsyncTask Promise 1 v8.5.0
JsGlobal global 1 v8.0.0
JsSymbol Symbol 1 v8.0.0
Int8Array/Uint8Array ... TypedArray 1 v8.0.0
JsFunction threadsafe function 4 v10.6.0 napi4
BigInt BigInt 6 v10.7.0 napi6

package-template's People

Contributors

brooooooklyn avatar dependabot[bot] avatar hyf0 avatar liby avatar lsndr avatar renovate[bot] avatar richerfu avatar talves avatar tristancamejo avatar wangziling avatar yisibl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

package-template's Issues

请问如何修改配置文件,来选择性的支持某些平台

如题,因为一些依赖库不跨平台,所以需要屏蔽某些平台。

是只需要修改 package.json 中 napi 下的 additional ,还是说 .github/workflows/CI.yml 也需要编辑?

有没有比较简单的配置办法? 比如修改某个配置文件,然后运行cli,模板生成CI.yml什么的

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

cargo
Cargo.toml
  • napi 2
  • napi-derive 2
  • napi-build 2
github-actions
.github/workflows/CI.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
  • goto-bus-stop/setup-zig v2
  • addnab/docker-run-action v3
  • actions/upload-artifact v4
  • actions/checkout v4
  • cross-platform-actions/action v0.25.0
  • actions/upload-artifact v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/download-artifact v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/download-artifact v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/download-artifact v4
  • actions/checkout v4
  • actions/download-artifact v4
  • docker/setup-qemu-action v3
  • addnab/docker-run-action v3
  • actions/checkout v4
  • actions/download-artifact v4
  • docker/setup-qemu-action v3
  • addnab/docker-run-action v3
  • actions/checkout v4
  • actions/download-artifact v4
  • docker/setup-qemu-action v3
  • addnab/docker-run-action v3
  • actions/checkout v4
  • actions/setup-node v4
  • actions/download-artifact v4
.github/workflows/lint.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
npm/android-arm-eabi/package.json
  • node >= 10
npm/android-arm64/package.json
  • node >= 10
npm/darwin-arm64/package.json
  • node >= 10
npm/darwin-x64/package.json
  • node >= 10
npm/freebsd-x64/package.json
  • node >= 10
npm/linux-arm-gnueabihf/package.json
  • node >= 10
npm/linux-arm64-gnu/package.json
  • node >= 10
npm/linux-arm64-musl/package.json
  • node >= 10
npm/linux-x64-gnu/package.json
  • node >= 10
npm/linux-x64-musl/package.json
  • node >= 10
npm/win32-arm64-msvc/package.json
  • node >= 10
npm/win32-ia32-msvc/package.json
  • node >= 10
npm/win32-x64-msvc/package.json
  • node >= 10
package.json
  • @napi-rs/cli ^2.18.4
  • @swc-node/register ^1.10.6
  • @swc/core ^1.6.13
  • @taplo/cli ^0.7.0
  • ava ^6.1.3
  • chalk ^5.3.0
  • husky ^9.0.11
  • lint-staged ^15.2.7
  • npm-run-all2 ^6.2.2
  • oxlint ^0.6.0
  • prettier ^3.3.3
  • tinybench ^2.8.0
  • typescript ^5.5.3
  • node >= 10
  • yarn 4.3.1

  • Check this box to trigger a request for Renovate to run again on this repository

Segmentation fault

I have a segmentation fault when loading my native module from a file.
Strangely if I load it from another topper file it's ok then.

I debugged via console.log the index.js entrypoint and the issue is coming when calling. getReports() fonction that lead to the segmentation fault.

So it even does not get the glibcVersionRuntime ,

If I import it elsewhere on my project it's ok and get the glibcVersionRuntime 2.28 and return false

Not sure what to do then..

Capture d’écran 2023-11-08 à 11 42 39

Unknown Syntax Error: Unsupported option name ("--pipe")

yarn run v1.22.17
$ napi build --platform --release --pipe "prettier -w"
Unknown Syntax Error: Unsupported option name ("--pipe").

$ napi build [--platform] [--release] [--config,-c #0] [--cargo-name #0] [--target #0] [--features #0] [--cargo-flags #0] [--cargo-cwd #0] [destDir]
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Segmentation fault when workers exit

I get segfaults on node 16 and node 18 when I use these in workers.

I'm on linux gnu x64


Replication steps:

Just run node segfault.js with:

segfault.js

var import_worker_threads = require("worker_threads");

if (import_worker_threads.isMainThread) {
  const worker = new import_worker_threads.Worker("./segfault");
} else {
  var import_napi_rs = require("@napi-rs/package-template");
}

If the parent thread has also imported it, it seems to work fine:

segfault.js with parent import:

var import_worker_threads = require("worker_threads");
var import_napi_rs = require("@napi-rs/package-template");

if (import_worker_threads.isMainThread) {
  const worker = new import_worker_threads.Worker("./segfault");
}

Support nightly in docker images

Hi,

Thanks for all the work on napi-rs!

I am trying to get a publish pipeline compiling using the nightly toolchain. For the builds that don't use docker this is pretty simple but I am not sure how I could update the musl builds that use docker to compile using the nightly toolchain. Any ideas?

Also, I noticed that for the x86_64-unknown-linux-gnu target building using docker seems to be redundant as it is using an ubuntu-latest image. See: https://github.com/napi-rs/package-template/blob/main/.github/workflows/CI.yaml#L40-L47

I switched it to just yarn build and it seems good or am i missing something here?

why use "cdylib" as crate-type?

I have a repo which contains a rust a binary foo and a napi-rs lib bar.

foo will import bar by local path link, but cdylib can't be used as dependency

Optional dependencies with Yarn issue

I have a project which use the template, I am not able or don't want to build for FREEBSD,

But magically the package.json on npm contains optionalDependencieswhich contains the FreeBDS one.

With nom , no problem, but with yarn it will lead to an error not found and the main package will not be installed

You can try with yarn install @avahq/resampler-native-rubato

Side question but why does. it even try to download it ? Does this means that it will download all binaries in my project ? (I supposed It was more like prebuild which get the only binary needed)

node16 no longer available in FreeBSD pipeline

Hello,

I'm currently working on a project that uses napi-rs, and noticed that the FreeBSD runner is no longer able to find node16 from the package manager. To verify this, I forked this template repo and tried running the pipelines on the fork. You can find the output here:

https://github.com/traeok/package-template/actions/runs/3661652187/jobs/6190049422

Aside from that, the other stages seem to be working as intended. Thanks for maintaining such an awesome library!

yarn config with the current script `yarn-4.3.1.cjs` breaks `.yarnrc.yml

When running the command yarn config set supportedArchitectures.cpu "arm" the following will format the file incorrectly:

nodeLinker: node-modules
    
    npmAuditRegistry: "https://registry.npmjs.org"
    
    supportedArchitectures:
      cpu: arm
    
    yarnPath: .yarn/releases/yarn-4.3.1.cjs

The script in yarn-4.3.1.cjs does not format the modules correctly across all systems.

Locally and on the github action.

github action trying to re-configure the yarn rc running the command yarn config set supportedArchitectures.libc "musl".

It works when using yarn-3.6.4.cjs.

yarn config set supportedArchitectures.cpu "arm" - working in terminal using yarn-3.6.4

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.