TimelordUK / node-sqlserver-v8

branched from node-sqlserver, SQL server driver compatible with all versions of Node
Other
135 stars 43 forks source link

Cannot use without 'require'? #305

Open jasong-au opened 10 months ago

jasong-au commented 10 months ago

The whole way that mssql and msnodesqlv8 work together seems wonky. It's taken a lot of time, but I got it to simply connect with plain javascript and using require. However I am trying to use it in a module (server-size sveltekit, but trying to get it working in node .mjs) and can't figure out how to get it to work without using 'require' which isn't supported. Any help or samples would be appreciated.

// This works in a plain .js file, but throws this error in an .mjs file
// *** ReferenceError: require is not defined in ES module scope, you can use import instead ***
// const sql = require('mssql/msnodesqlv8')

// Trying to change it to an import gives an error:
// *** Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\git\t\mssql\node_modules\mssql\msnodesqlv8' imported from C:\git\t\mssql\index.mjs ***
import * as sql from 'mssql/msnodesqlv8'
TimelordUK commented 10 months ago

I am afraid i do not have any association with this module, so cannot help - does this work?


import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const sql= require('mssql/msnodesqlv8')
const connectionString  = "Driver={ODBC Driver 17 for SQL Server};Server=(localdb)\\node;Database=scratch;Trusted_Connection=yes;"

const config = {
    connectionString: connectionString
}

async function runner() {
    const pool = await sql.connect(config)
    const res = await pool.query('select top 3 * from syscolumns')
    console.log(JSON.stringify(res, null, 4))
    await pool.close()
}

runner().then(() => {
    console.log('done')
})