Toby King
Toby King

Reputation: 129

Uncaught ReferenceError: require is not defined in svelte/sapper

Trying to create a blog-like application using svelte/sapper and so I'm currently writing the post to a file as a JSON object. However, when I try and use fs, I get the following error:

Uncaught ReferenceError: require is not defined

The file below is in the src/routes folder and is what handles the file writing function:

_write.js

function writeFile(obj) {
  var fs = require("fs");
  fs.writeFile('C:/Users/Toby/Documents/GitHub/political-web/src/routes/_posts.js', 'const posts = ' + obj + '; export default posts;', function (err) {
    if (err) throw err;
    console.log('Done!');
  });
}

export default writeFile;

Any ideas as to what I'm doing wrong?

Upvotes: 3

Views: 4433

Answers (1)

Rich Harris
Rich Harris

Reputation: 29605

Not sure why you're getting that specific error — require should be defined when that code runs, unless you're somehow importing it in your client app (e.g. via a component).

Assuming that's not the case, and you're only importing _write.js from server code, rewrite it like this:

import fs from 'fs';

function writeFile(obj) {
  fs.writeFile('C:/Users/Toby/Documents/GitHub/political-web/src/routes/_posts.js', 'const posts = ' + obj + '; export default posts;', function (err) {
    if (err) throw err;
    console.log('Done!');
  });
}

export default writeFile;

Upvotes: 1

Related Questions