foliojs / pdfkit

A JavaScript PDF generation library for Node and the browser
http://pdfkit.org/
MIT License
9.91k stars 1.15k forks source link

Error: ENOENT: no such file or directory, open '//data.trie' #990

Closed stanurio2017 closed 3 years ago

stanurio2017 commented 5 years ago

Question

Error while loading

How to solve this? Error: ENOENT: no such file or directory, open '//data.trie'

Code sample

const PDFDocument = require('pdfkit'); const fs = require('fs'); const doc = new PDFDocument();

export class PdfStreamDataService { constructor() { }

public execute = function () {

        doc.pipe(fs.createWriteStream('out.pdf'));
        // Set some meta data
        doc.info['Title'] = 'Test Document';
        doc.info['Author'] = 'Test name';

        // Register a font name for use later
        // doc.registerFont('Palatino', 'fonts/PalatinoBold.ttf');

        var loremIpsum =
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;\nMauris at ante tellus. Vestibulum a metus lectus. Praesent tempor purus a lacus blandit eget gravida ante hendrerit. Cras et eros metus. Sed commodo malesuada eros, vitae interdum augue semper quis. Fusce id magna nunc. Curabitur sollicitudin placerat semper. Cras et mi neque, a dignissim risus. Nulla venenatis porta lacus, vel rhoncus lectus tempor vitae. Duis sagittis venenatis rutrum. Curabitur tempor massa tortor.';

        // Draw some text wrapped to 412 points wide
        doc
        .text('And here is some wrapped text...', 100, 300)
        .font('Helvetica', 13)
        .moveDown()
        .text(loremIpsum, {
            // move down 1 line
            width: 412,
            align: 'justify',
            indent: 30,
            paragraphGap: 5
        });

        doc.end();
}

}

Your environment

thalesagapito commented 5 years ago

I've been having the exact same problem, are you also using Typescript? Disabling Typescript solved it for me. I know it's not a viable solution in most cases, but it might point somewhere.

johanbyren commented 5 years ago

Same problem for me, I will get back here if I find a solution.

Pzixel commented 5 years ago

I have an issue with webpacked solution

$ node dist/app.js
fs.js:646
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open 'C:\data.trie'
    at Object.fs.openSync (fs.js:646:18)
    at Object.fs.readFileSync (fs.js:551:33)
    at Module.<anonymous> (path\dist\app.js:337:54340)
    at Module.n (path\dist\app.js:337:54384)
    at r (path\dist\app.js:1:172)
    at Object.<anonymous> (path\dist\app.js:71:4203)
    at Object.<anonymous> (path\dist\app.js:71:256427)
    at r (path\dist\app.js:1:172)
    at Module.<anonymous> (path\dist\app.js:320:3088)
    at Module.<anonymous> (path\dist\app.js:320:85735)

Although works fine on dev machine with node_modules directories.

Any solutions for it?

blikblum commented 5 years ago

@Pzixel

I have an issue with webpacked solution

There's some error in your webpack configuration

You can look here a working webpack configuration: https://github.com/blikblum/pdfkit-webpack-example

Alternatively you can use https://www.npmjs.com/package/pdfkit-next that is browser friendly

Pzixel commented 5 years ago

I'm actually not using it in browser, I'm using it on node.js installation. Althout I want to public some minimal distribution instead of sharing 200mb of dependencies. I can't share my config now but I can do it tomorrow.

nicolaaretini commented 5 years ago

@blikblum I see your solution but none of them was working for me.

I'm also getting this error:

{ Error: ENOENT: no such file or directory, open '//data.trie' at Object.openSync (fs.js:443:3) at Object.readFileSync (fs.js:343:35)

I'm creating a lambda using Typescript, serverless; scaffholding through temaplate: $ serverless create --template aws-nodejs-typescript && npm install

This is the webpack.config.js (which is the default from the above aws-nodejs-typescript template):

`const path = require('path'); const slsw = require('serverless-webpack');

const entries = {};

Object.keys(slsw.lib.entries).forEach( key => (entries[key] = ['./source-map-install.js', slsw.lib.entries[key]]) );

module.exports = { mode: slsw.lib.webpack.isLocal ? 'development' : 'production', entry: entries, devtool: 'source-map', resolve: { extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'], }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: '[name].js', }, target: 'node', module: { rules: [ // all files with a .ts or .tsx extension will be handled by ts-loader { test: /.tsx?$/, loader: 'ts-loader' }, ], }, };`

blikblum commented 5 years ago

You need add brfs transform. See config of the example i linked above

Pzixel commented 5 years ago

Here is my repo: https://github.com/Pzixel/PDFKit-example.git

As you can see I add "brfs" transformation.

However, it doesn't work to me:

image

blikblum commented 5 years ago

You are applying brfs to ts files. You should create a specific rule for js files.

Pzixel commented 5 years ago

I didn't (if you can see there was JS rules), and adding TS files to rule set doesn't change it (see most recent commit).

So it still doesn't work. I'd appreciate if you clone the repo and make sure it doesn't work. You could add some fixed there so everybody could find out how to fix the issue.

tobloef commented 5 years ago

I'm having this exact problem as well, when trying to use the module on a webpacked node.js server.

blikblum commented 5 years ago

I created a PR fixing https://github.com/Pzixel/PDFKit-example/pull/1

webpack try to use es module version even on node which brfs does not supports. brfs also dont like babel interopDefault helper

realfresh commented 4 years ago

If anyone is looking for a simple temporary solution, you can download the standalone js file at https://github.com/foliojs/pdfkit/releases/download/v0.10.0/pdfkit.standalone.js

Then just require that in code.

BenJHarris commented 4 years ago

I created a PR fixing https://github.com/Pzixel/PDFKit-example/pull/1

webpack try to use es module version even on node which brfs does not supports. brfs also dont like babel interopDefault helper

@blikblum @Pzixel

Looks like you found a solution, however that repo is no longer public - do you have any details of what the solutions was?

Pzixel commented 4 years ago

I actually didn't manage to make it work with webpack so I don't pack it. I decided that extra 50mb in docker image is better than spending days for a solution.

I wonder why repo is missing. Did I delete it by accident? Going to ask support if they could restore it.


Support helped me to restore the repository, now it's available

brpsmith commented 3 years ago

In case someone hits this issue in the future. I was able to address this error by adding the following to the module.rules in the repo/webpack.config https://github.com/Pzixel/PDFKit-example.git

{test: /unicode-properties[/\]unicode-properties.cjs.js$/, loader: "transform-loader?brfs"},

The primary issue for me was that webpack was using the es, not cjs file for unicode-properties/unicode-properties.cjs.js and in turn not inlining the data.trie file contents via the transform-loader?brfs

jwoptio commented 3 years ago

I was finally able to get this working server side with webpack using config from the example webpack.config at Pzixel/PDFKit-example.git as mentioned above although I had to add all of the following:

...
const StringReplacePlugin = require("string-replace-webpack-plugin");
...
module.exports = {
    ...
    resolve: {
        ...
        alias: {
          'unicode-properties': 'unicode-properties/unicode-properties.cjs.js',
          'pdfkit': 'pdfkit/js/pdfkit.js'
        }
    },
    plugins: [new StringReplacePlugin()],
    module: {
        rules: [
            ...
            {
              enforce: 'pre',
              test: /unicode-properties[\/\\]unicode-properties/,
              loader: StringReplacePlugin.replace({
                replacements: [
                  {
                    pattern: "var fs = _interopDefault(require('fs'));",
                    replacement: function () {
                      return "var fs = require('fs');";
                    }
                  }
                ]
              })
            },
            {test: /unicode-properties[\/\\]unicode-properties/, loader: "transform-loader?brfs"},
            {test: /pdfkit[/\\]js[/\\]/, loader: "transform-loader?brfs"},
            {test: /fontkit[\/\\]index.js$/, loader: "transform-loader?brfs"},
            {test: /linebreak[\/\\]src[\/\\]linebreaker.js/, loader: "transform-loader?brfs"}            
        ]
    }
};

You need to npm/yarn install transform-loader and string-replace-webpack-plugin to get this to work.

youbek commented 3 years ago

I was finally able to get this working server side with webpack using config from the example webpack.config at Pzixel/PDFKit-example.git as mentioned above although I had to add all of the following:

...
const StringReplacePlugin = require("string-replace-webpack-plugin");
...
module.exports = {
    ...
    resolve: {
      ...
        alias: {
          'unicode-properties': 'unicode-properties/unicode-properties.cjs.js',
          'pdfkit': 'pdfkit/js/pdfkit.js'
        }
    },
    plugins: [new StringReplacePlugin()],
    module: {
        rules: [
            ...
            {
              enforce: 'pre',
              test: /unicode-properties[\/\\]unicode-properties/,
              loader: StringReplacePlugin.replace({
                replacements: [
                  {
                    pattern: "var fs = _interopDefault(require('fs'));",
                    replacement: function () {
                      return "var fs = require('fs');";
                    }
                  }
                ]
              })
            },
            {test: /unicode-properties[\/\\]unicode-properties/, loader: "transform-loader?brfs"},
            {test: /pdfkit[/\\]js[/\\]/, loader: "transform-loader?brfs"},
            {test: /fontkit[\/\\]index.js$/, loader: "transform-loader?brfs"},
            {test: /linebreak[\/\\]src[\/\\]linebreaker.js/, loader: "transform-loader?brfs"}            
        ]
    }
};

You need to npm/yarn install transform-loader and string-replace-webpack-plugin to get this to work.

Dude, you saved my day!

blikblum commented 3 years ago

A webpack 5 example can be found at https://github.com/foliojs/pdfkit/tree/master/examples/webpack

dereekb commented 2 years ago

From anyone coming here with an Nx.dev project that is building a stand-alone nodejs script, I had trouble getting any of the above solutions to work as they were when trying to generate main.js with all externalDependecies packaged (externalDependencies: "none"). The final config that worked for me:

webpack.config.js

module.exports = (config, context) => {
  return {
    ...config,
    resolve: {
      ...config.resolve,
      alias: {
        ...config.resolve.alias,
        'unicode-properties': 'unicode-properties/unicode-properties.cjs.js',
        'pdfkit': 'pdfkit/js/pdfkit.js'
      }
    },
    module: {
      ...config.module,
      rules: [
        ...config.module.rules,
        {
          enforce: 'pre',
          test: /unicode-properties[\/\\]unicode-properties/,
          loader: 'string-replace-loader',
          options: {
            search: "var fs = _interopDefault(require('fs'));",
            replace: "var fs = require('fs');"
          }
        },
        {
          enforce: 'post',
          test: /unicode-properties[\/\\]unicode-properties/,
          loader: 'transform-loader',
          options: {
            brfs: {}
          }
        },
        {
          enforce: 'post',
          test: /pdfkit[/\\]js[/\\]/,
          loader: 'transform-loader',
          options: {
            brfs: {}
          }
        },
        {
          enforce: 'post',
          test: /fontkit[/\\]index.js$/,
          loader: 'transform-loader',
          options: {
            brfs: {}
          }
        },
        {
          enforce: 'post',
          test: /linebreak[/\\]src[/\\]linebreaker.js/,
          loader: 'transform-loader',
          options: {
            brfs: {}
          }
        }
      ]
    }
  };
};

project.json

 "build": {
      "executor": "@nrwl/node:build",
      ...
      "options": {
      ...
        "externalDependencies": "none",
        "webpackConfig": "packages/make-qrcodes/webpack.config.js",
      ...
      }
    },

Dependencies / package.json

    "string-replace-loader": "^3.1.0",
    "transform-loader": "^0.2.4",