I have created a node module following this recipe:
mkdir addon
cd addon
npm init -y
npm install --save-dev node-gyp
npm install node-addon-api
Create the file addon.cc:
#include <napi.h>
Napi::String Hello(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
return Napi::String::New(env, "Hello from C++!");
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "hello"),
Napi::Function::New(env, Hello));
return exports;
}
NODE_API_MODULE(addon, Init)
create the file binding.gyp
{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ],
'include_dirs': [
"<!@(node -p "require('node-addon-api').include")"
],
'libraries': [],
'dependencies': [
"<!(node -p "require('node-addon-api').gyp")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}
]
}
npm configure
npm build
copy the file addon/build/Release/addon.node
> lib/addon/addon.node
Create a file in app/api/test/route.ts
import { NextResponse } from "next/server";
const myAddon = require("/lib/addon/addon.node")
export async function GET() {
try {
const result = myAddon.hello();
return NextResponse.json({
message: result
});
} catch(error) {
return NextResponse.json({
message: error.message
});
}
}
in app/page.tsx
I have:
"use client";
import { useEffect, useState } from "react";
export default function Home() {
const [message, setMessage] = useState<string>("default");
const getData = async () =>
fetch("/api/hello")
.then(function (response) {
return response.text();
})
.then(function (data_raw) {
const data = JSON.parse(data_raw);
setMessage(data.message);
});
useEffect(() => {
getData();
}, []);
return (
<main className="p-24">
{message}
</main>
);
}
I get the error when running npm run dev
:
[NEXT] Import trace for requested module:
[NEXT] ./lib/addon/addon.node
[NEXT] ./src/app/api/hello/route.ts
[NEXT] ⨯ ./lib/addon/addon.node
[NEXT] Module parse failed: Unexpected character '�' (1:2)
[NEXT] You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
[NEXT] (Source code omitted for this binary file)
Why do I get this “unexpected character”? How can I fix it?