ttt
ttt

Reputation: 69

How Do I use a node.js module with Next.js?

Do I need to use express with next.js?

Im trying to add this code into a next.js application. ( from npm module example code: pdf2json )

let fs = require('fs');
var PDFParser = require("pdf2json");
let pdfParser = new PDFParser(this,1);

pdfParser.on("pdfParser_dataError", errData => 
   console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", pdfData => {
fs.writeFile("./sometxt.txt", pdfParser.getRawTextContent());
pdfParser.loadPDF("./page1.pdf");

Upvotes: 3

Views: 8842

Answers (2)

Ramo
Ramo

Reputation: 187

You can require it conditionally by testing if it is the server:

static async getInitialProps({isServer}){
 var fs;
 if(isServer){
  fs=require('fs');
  //and do what ever you want
 }
}

and dot not forgot to tell webpack to do not send the module to the client side by changing package.json like so:

  "browser": {
    "fs": false
  }

unless it can produce errors.

Upvotes: 3

Nathan Friedly
Nathan Friedly

Reputation: 8146

The thing that's probably biting you is that most of your code must work on both the client and the server. You can write server-only code by creating a getInitialProps() method and checking to see if it's passed in a opts.req - if so, you know the code is running server-side and you can hit the filesystem:

import React from 'react'

const doServerSideStuff = () => {
    let fs = require('fs');
    var PDFParser = require("pdf2json");
    let pdfParser = new PDFParser(this,1);

    pdfParser.on("pdfParser_dataError", errData => 
       console.error(errData.parserError) );
    pdfParser.on("pdfParser_dataReady", pdfData => {
    fs.writeFile("./sometxt.txt", pdfParser.getRawTextContent());
    pdfParser.loadPDF("./page1.pdf");
}

export default class extends React.Component {
  static async getInitialProps ({ req }) {
    if (req) {
      doServerSideStuff();
    }
    return {};
  }
  render () {
    return <div> Hello World </div>
  }
}

This isn't really a complete example yet, you should really make doServerSideStuff() async (or return a promise) and then await it in getInitialProps, and eventually return props that represent the result of the parsing & saving. Also, handle fs.writeFile errors. But, hopefully it's enough to get you going in the right direction.

See the docs for some more info on this.

Or you could just use Express like you suggested. There is a good tutorial and example code that should help you get started if you decide to go that route.

Upvotes: 0

Related Questions